Laravel从第三个表返回属性


Laravel return property from third table

我有三个表:

products
product_types
product_categories

products属于product_typesproduct_types属于product_categories

如何从product_categories访问列 products

产品类型型号:

class ProductTypes extends Eloquent {
    public function category() {
        return $this->belongsTo('ProductCategories');
    }
}

产品型号:

class Product extends Eloquent {
    protected $table = 'products';
    public function brands() {
        return $this->belongsTo('ProductBrands', 'brand_id', 'id');
    }
    public function ages() {
        return $this->belongsTo('ProductAges', 'age_id', 'id');
    }
    public function types() {
        return $this->belongsTo('ProductTypes', 'type_id', 'id');
    }
    public function images() {
        return $this->hasMany('ProductImages');
    }
    public function reviews() {
        return $this->hasMany('ProductReviews');
    }
    public function toArray() {
        $ar = $this->attributes;
        $ar['brand'] = $this->brand;
        $ar['age'] = $this->age;
        $ar['type'] = $this->type;
        return $ar;
    }
    public function getBrandAttribute() {
        $brands = $this->brands()->first();
        return (isset($brands->brand) ? $brands->brand : '');
    }
    public function getAgeAttribute() {
        $ages = $this->ages()->first();
        return (isset($ages->age) ? $ages->age : '');
    }
    public function getTypeAttribute() {
        $types = $this->types()->first();
        return (isset($types->type) ? $types->type : '');
    }
}

我试过:

$productData->types()->category()->category

但这给出了一个错误,指出该方法不存在。

对不起标题,想不出一个。

问题是,您在执行types()时没有执行查询,因此您在查询生成器实例而不是ProductTypes模型上调用category()

可以使用动态属性来访问关系的结果

$productData->types->category->category

还可以考虑重命名您的关系。例如,当前您有"类型",但它只返回一种类型,因为它是一对多关系。"类型"会更有意义。