更新时间:2023-02-22 17:07:13
您的问题是您使用的是Laravel的查询生成器
Your issue is that you're using Laravel's query builder instead of Eloquent, but you're treating the result as if it was Eloquent.
当您这样做时:
$products = DB::table('products')->where('user_id', $user_id)->paginate(5);
$ products
变量将包含 Paginator
实例,其中包含您的商品作为 stdClass
的实例。如果您希望能够使用Eloquent进行此操作,则应尝试以下操作:
The $products
variable will contain a Paginator
instance, which contains your items as instances of stdClass
. If you want to be able to do this with Eloquent, you should try something like this:
$products = Product::with('category')->where('user_id', $user_id)->paginate(5);
这将确保在分页器中返回的商品是您的产品的实例
雄辩的模型,渴望加载 category
关系(即,它将为每个 Product $ c加载类别关系$ c>使用一个查询(而不是5个查询)返回,每个
产品
)一个查询。
This will ensure that the items returned in the paginator are instances of your Product
Eloquent model, with the category
relationship eager loaded (I.e. it will load the category relationship for each Product
returned using one query, rather than 5 queries, one for every Product
).
然后能够访问 $ product-> category->名称
。