dongxiang3205 2014-04-22 16:33
浏览 21
已采纳

检索Laravel中的相关模型

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
  • 写回答

1条回答 默认 最新

  • douyi6168 2014-04-22 16:45
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败