如何 return 为 laravel 中的关系建模?

How to return model with relationsip in laravel?

我有两个模型 ProductCategory

categories table 有 idname 列。

虽然 products table 有 idnamecategory_id [foreign_key 到类别].


这是我的以下代码(已经有值为 1 的类别,“学校用品”):

$product = new Product;
$product->category_id = 1;
$product->name = "pencil";
$product->save();

return $product->with('category');

我的问题是为什么当我尝试使用关系模型获取数据时 returns 出现以下错误?有人知道具体怎么做吗?

[34;4mIlluminate\Database\Eloquent\Builder[39;24m {#4069}

您可以使用 load 方法而不是 with 延迟预加载关系。

with 用于预先加载。

$product->load('category');
return $product;