[英]How Do Inverse Relationships Work in Laravel Eloquent?
I have two models/tables: publisher
and campaign.
我有两个模型/表格:
publisher
和campaign.
Publisher 出版者
id | name
Campaign 运动
id | name | PubID
I created a relationship to get the Publisher's campaigns. 我创建了一个关系来获取发布者的广告系列。
$this->hasMany(Campaign::class, 'PubID'); /* In Publisher Model */
I believe the above line will help me to retrieve relevant campaigns, but I'm confused about the inverse relationship. 我相信以上内容将帮助我检索相关的广告系列,但是我对逆向关系感到困惑。
As you can see, there is no key campaign_id
inside the publisher
table. 如您所见,
publisher
表中没有键campaign_id
。 Would the below relationship be enough for the inverse? 下面的关系足以满足反要求吗?
return $this->belongsTo('App\Publisher'); /* In Campaign Model */
Can someone kindly guide me? 有人可以指导我吗? I would appreciate it.
我会很感激。
Yes, this is so called one to many relationship
, which means one publisher has many campaigns. 是的,这就是所谓的
one to many relationship
,这意味着一个发布者拥有许多广告系列。 And the inverse is that a campaign belongs to a publisher. 相反的是,活动属于发布者。 So in order to get all the campaigns for the publisher you use:
因此,为了获得发布商的所有广告系列,您可以使用:
Publisher::find($id)->campaigns;
In order to get what is the publisher of the campaign, you use: 为了获得活动的发布者,您可以使用:
Campaign::find($id)->publisher;
You don't need campaign_id
inside the publisher table, that is known by the PubID
in your campaign table. 您不需要在发布者表中使用
campaign_id
,而在广告系列表中, PubID
就是已知的。
You ,eed to specify the foreign key name in the belongsTo 您需要在belongsTo中指定外键名称
return $this->belongsTo('App\Publisher','PubID');
You have two models and adding two foreign id. 您有两个模型,并添加了两个外部ID。 It is a many to many working.
这是许多工作。 You just need add pivot table with campain_id and publiser_id
您只需要添加带有campain_id和publiser_id的数据透视表
It's a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher. 这是多对多关系的一个很好的例子:一个发布者可以属于多个活动对象,而一个活动者可以具有多个发布者。
publishers 出版商
ID | ID | NAME
名称
campaigns 活动
ID | ID | NAME
名称
campaign_publisher campaign_publisher
campain_id | campain_id | publisher_id
PUBLISHER_ID
The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title. 列表中的最终表– campaign_publisher称为“数据透视表”,如主题标题中所述。
So, option 1: 因此,选项1:
class Campaign extends Model
{
/**
* The products that belong to the shop.
*/
public function publishers()
{
return $this->belongsToMany('App\Publisher');
}
}
So, option 2: 因此,选项2:
class Publisher extends Model
{
/**
* The shops that belong to the product.
*/
public function campaigns()
{
return $this->belongsToMany('App\Campaign');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.