我想列出所有广告系列及其与数据库的关系。 这是现在的代码。
Campaign.php
public function task(){
return $this->hasMany('Task','campaign_id');
}
}
?>
Task.php
public function campaign(){
return $this->belongsTo('Campaign','campaign_id');
}
}
?>
和Page控制器
public function campaigns(){
return View::make('pages.platform.campaigns')
->with('campaigns', Campaign::all());
}
这样做的时候我这样做了:
<pre>
@foreach($campaigns as $c)
<? print_r($c) ?>
@endforeach
</pre>
我看不到关系
[relations:protected] => Array()
如何访问此相关模型,以便我可以回复它们,如
$c['name'] // Name field in Campaign table
$c['task']['name'] // Name field in related Task table
答案 0 :(得分:1)
这很简单:
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
}
}
但上面的内容将导致foreach循环中每个广告系列的数据库查询,因此在您的控制器中更改:
->with('campaigns', Campaign::all());
// to this:
->with('campaigns', Campaign::with('task')->get());
with()方法负责急切加载 - 检查是否必须。 http://laravel.com/docs/eloquent#eager-loading
然后我建议你的关系适当地调用关系本身,所以对于belongsTo或hasOne和复数为hasMany,belongsToMany,hasManyThrough等。
话虽如此,我会称之为你的关系:
// Campaign model
public function tasks()
{
...
}
然后你当然用with()方法而不是'task'来引用'tasks'。