sag*_*290 2 php relationship laravel eloquent laravel-5.6
我知道它的基本原理,但无法弄清楚问题出在哪里。看来我做的一切都是对的。我想与产品品牌建立关系,其中每个产品都有一个属于品牌的品牌 ID,而且在品牌模型中每个品牌都有许多产品。我使用belongsTo有很多关系来做到这一点,但它仍然向我显示错误。
Product.php模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'sku',
'name',
'description',
'brand_id',
'image',
'price',
'stocks',
'color',
'size',
];
protected $table = 'products';
public function brand() {
return $this->belongsTo('App\Brand');
}
}
Run Code Online (Sandbox Code Playgroud)
Brand.php模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
protected $fillable = [
'user_id',
'name',
'description'
];
protected $table = 'brands';
public function products() {
return $this->hasMany('App\Product','brand_id', 'id');
}
}
Run Code Online (Sandbox Code Playgroud)
routs.php
Route::get('/', function () {
$products = \App\Product::all();
echo $products->brand();
});
Run Code Online (Sandbox Code Playgroud)
$products是对象的集合Product,因此要获取每个对象的品牌,您需要迭代该集合:
foreach ($products as $product) {
echo $product->brand->name;
}
Run Code Online (Sandbox Code Playgroud)