我有我的模型产品:
class Product extends Model
{
protected $table = 'products';
protected $primaryKey = 'id_product';
protected $fillable = [
'id_category', 'title', 'credit', 'created_at', 'updated_at',
];
public function categories()
{
return $this->belongsToMany('App\Category', 'products_categories', 'id_product', 'id_category');
}
}
我有我的分类模型:
class Category extends Model
{
protected $table = 'categories';
protected $primaryKey = 'id_category';
protected $fillable = [
'category', 'created_at', 'updated_at',
];
public function products()
{
return $this->belongsToMany('App\Product', 'products_categories', 'id_product', 'id_category');
}
}
我有我的table products_categories
我想列出属于某个类别的产品,所以我这样做:
$products = Product::with('categories')->get();
foreach ($products as $product) {
$products->title;
}
但它不起作用,我想知道......我怎么能列出?
我已经尝试了所有..并且它表示此集合实例上不存在Property [title]。
由于
答案 0 :(得分:2)
您看到的错误可能是由于输入错误造成的。它应该是:
foreach ($products as $product) {
$product->title;
}
除此之外,其余代码看起来不错。修复拼写错误应该允许您访问每个产品'类别来自:
foreach ($products as $product) {
foreach ($product->categories as $category) {
$category->name // or other attribute
}
}