"Method brand does not exist."

"Method brand does not exist."

我知道它的基本原理,但无法弄清楚问题出在哪里。看起来我做的一切都是对的。我想与产品品牌建立关系,其中每个产品都有一个属于品牌的品牌 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();

});

$productsProduct 对象,因此要为每个对象获取品牌,您需要遍历集合:

foreach ($products as $product) {
    echo $product->brand->name;
}

编辑

您可以使用高阶函数来简化循环:

$products->each->brand->name

您正在通过集合数据调用该方法。

您应该先循环产品,并且在使用关系时不需要左括号。

而不是

$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;

}

希望这会启发你。