Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

php - Laravel 5相反的belongsToMany(Laravel 5 Inverse of belongsToMany)

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 adding brand_id on my products table and do the relationship thing on my Product model.

(可以肯定的是,通过在我的products表上添加brand_id并在我的产品模型上执行关联操作,可以实现我想要的功能。)

However, I have an above database structure.

(但是,我有一个上面的数据库结构。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your assumption of adding a brand_id on products is correct.

(您在产品上添加brand_id假设是正确的。)

What you are describing is a one-to-many relationship, but a database structure representing a many-to-many.

(您所描述的是一对多关系,但是一个表示多对多关系的数据库结构。)

Remove the pivot table and add the brand id to the products table and you'll be good to go.

(删除数据透视表并将品牌ID添加到产品表中,您就可以开始使用了。)

// Product model
public function brand()
{
    return $this->belongsTo(Brand::class);
}

// Brand model
public function products()
{
    return $this->hasMany(Product::class);
}

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

(https://laravel.com/docs/5.5/eloquent-relationships#one-to-many)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...