actually not sure if I am doing it correctly or there are other ways.
(实际上不确定我是否正确执行操作或有其他方法。)
What I have in my database are the following(我数据库中的内容如下)
brands
id: integer
name: string
slug: string
description: string
timestamp
products
id: integer
name: string
price: decimal
slug: string
description: string
timestamp
brand_product
id: integer
brand_id: unsignedInteger
product_id: unsignedInteger
Basically, brands have many products, so on my Brand model
(基本上,品牌有很多产品,所以我的品牌模型)
...
public function products()
{
return $this->belongsToMany(Product::class);
}
...
However, a Product has one (1) Brand model.
(但是,产品具有一(1)个品牌模型。)
Pretty sure I can achieve what I want by addingbrand_id
on my products
table and do the relationship thing on my Product model. (可以肯定的是,通过在我的products
表上添加brand_id
并在我的产品模型上执行关联操作,可以实现我想要的功能。)
(但是,我有一个上面的数据库结构。)
What I did, on my Product model:(在产品模型上我做了什么:)
...
protected $appends = ['brand'];
public function brand()
{
return $this->belongsToMany(Brand::class);
}
public function getBrandAttribute()
{
return $this->brand()->first();
}
...
ask by Jay Are translate from so