我知道它的基本但却无法弄清楚问题是什么。看起来我做的一切都是正确的。我想与产品品牌建立关系,其中每个产品都有品牌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');
}
}
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');
}
}
routs.php
Route::get('/', function () {
$products = \App\Product::all();
echo $products->brand();
});
答案 0 :(得分:4)
combineLatest
是$products
个Product
个对象,因此要为每个对象获取品牌,您需要遍历该集合:
foreach ($products as $product) {
echo $product->brand->name;
}
答案 1 :(得分:2)
修改的
您可以使用更高阶函数来简化循环:
$products->each->brand->name
答案 2 :(得分:2)
您通过收集数据调用该方法。
您应首先循环产品,并且在使用关系时不需要打开的右括号。
而不是
$products = \App\Product::all();
echo $products->brand();
应该是这样的。
$products = \App\Product::all();
foreach($products as $index => $product){
echo $product->brand; //however this will return the Brand model and you can't echo a Model instead display the data via print_r or put it in $variable. then use the $variable as how you handle a model Data.
$brand = $product->brand;
echo $brand->name;
echo $brand->description;
}
希望这会让你感到高兴。