简体   繁体   English

在Laravel中检索相关模型

[英]Retrieving related models in Laravel

I want to list all campaigns with their relations from database. 我想从数据库中列出所有活动及其关系。 Here is the code for now. 这是现在的代码。

Campaign.php Campaign.php

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

Task.php 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: 但以上内容将导致foreach循环中每个广告系列的数据库查询,因此在您的控制器中进行更改:

->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. with()方法负责快速加载-请务必检查。 http://laravel.com/docs/eloquent#eager-loading 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. 然后,我建议对关系本身适当地调用您的关系,所以对belongsTo或hasOne来说是单数,对hasMany,belongsToMany,hasManyThrough等来说是复数。

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'. 然后,当然可以在with()方法中引用“任务”,而不是“任务”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM