mardi 23 février 2016

Laravel 5 - relationships between models

I have a database structure as follows.

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
--------------------------------------------

Within my Campaign Model, I have

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

Within CampaignCreatives I have

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

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

And within CampaignCreativesData

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

The theory behind this is a Campaign can have One CampaignCreatives. A CampaignCreatives can have one or more CampaignCreativesData.

I am not too sure if my Models are correct for this? I have a feeling it is not. Reason I say this is that within one of my views, if I do

{{ dd($campaignCreative) }}

I can see the information relating to the campaignCreative. However, if I do

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

I get the warning

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

Are my relationships set up appropriately, or am I doing something wrong with the foreign keys?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire