سؤال

I want to list all campaigns with their relations from database. Here is the code for now.

Campaign.php

        public function task(){
            return $this->hasMany('Task','campaign_id');
        }
    }
?>

Task.php

        public function campaign(){
            return $this->belongsTo('Campaign','campaign_id');
        }
    }
?>

And Page controller

public function campaigns(){
    return View::make('pages.platform.campaigns')
    ->with('campaigns', Campaign::all());
}

It this case when I do this:

<pre>
    @foreach($campaigns as $c)
        <? print_r($c) ?>
    @endforeach
</pre>

I can't see the relations

[relations:protected] => Array()

How can I access this related models so I can echo them like

$c['name'] // Name field in Campaign table
$c['task']['name'] // Name field in related Task table
هل كانت مفيدة؟

المحلول

It's as simple as this:

foreach ($campaigns as $campaign)
{
  $campaign->name; // campaign model property

  foreach ($campaign->task as $task) // $campaign->task is a collection (hasMany relation)
  {
    $task; // related Task model
    $task->name; // with accessible all its properties
  }
}

but the above will cause database query for every campaign in the foreach loop, so in your controller change:

->with('campaigns', Campaign::all());
// to this:
->with('campaigns', Campaign::with('task')->get());

with() method is responsible for eager loading - check that as it's a must. http://laravel.com/docs/eloquent#eager-loading

Then I suggest calling your relations appropriately to the relation itself, so singular for belongsTo or hasOne and plural for hasMany, belongsToMany, hasManyThrough etc.

That being said, I would call the relation of your like this:

// Campaign model
public function tasks()
{
  ...
}

Then of course you refer to 'tasks' in with() method instead of 'task'.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top