Laravel 5 - 模型之间的关系

时间:2016-02-23 16:11:19

标签: laravel laravel-5 laravel-5.1

我的数据库结构如下。

campaign

id    | name         | ...
----------------------
5     | something    | ...
----------------------

campaign_creatives

id    | type         | campaignId
---------------------------------
1     | something    | 5
---------------------------------

campaign_creatives_data

id | name       | campaignCreativesId
--------------------------------------------
1  | something  | 1
--------------------------------------------
2  | something  | 1
--------------------------------------------
3  | something  | 1
--------------------------------------------

在我的广告系列模型中,我有

public function campaignCreatives()
{
    return $this->hasOne('App\CampaignCreatives', 'campaignId');
}

在CampaignCreatives中我有

public function campaign()
{
    return $this->belongsTo('App\Campaign');
}

public function campaignCreativesData()
{
    return $this->hasMany('App\CampaignCreativesData', 'campaignCreativesId');
}

在CampaignCreativesData

public function campaignCreatives()
{
    return $this->belongsTo('App\CampaignCreatives');
}

这背后的理论是一个运动可以有一个CampaignCreatives。 CampaignCreatives可以有一个或多个CampaignCreativesData。

我不太确定我的模型是否正确?我有一种感觉它不是。原因我说这是我的一个观点,如果我这样做

{{ dd($campaignCreative) }}

我可以看到与campaignCreative相关的信息。但是,如果我这样做

{{ dd($campaignCreative->campaignCreativesData) }}

我收到了警告

Undefined property: Illuminate\Database\Eloquent\Collection::$campaignCreativesData

我的关系是否设置得恰当,或者我是否对外键做错了?

由于

2 个答案:

答案 0 :(得分:1)

你需要遍历该集合

@foreach ($campaignCreative->campaignCreativesData as $campaignCreativesData)
{{ $campaignCreativesData->name }}
@endforeach

答案 1 :(得分:0)

试试这个

{{ dd($campaignCreative->campaignCreativesData()) }}