Laravel属于关系存在

时间:2016-07-11 08:36:10

标签: php laravel-4

我有客户与他的项目之间的当前关系

项目模型

public function client()
{
    return $this->belongsTo('Client', 'cid');
}

项目控制器

public function index() {
    $projects = Project::with('client')->orderBy('pid', 'desc')->get();
    $this->layout->content = View::make('projects.index')->with('projects', $projects);
}

现在一切正常,我可以从项目视图中获取有关客户端的所有信息。但是,如果数据库中不存在客户端ID(在客户端表中),则会出现错误"尝试获取非对象的属性。"我希望能够发送一个空对象,而不是得到这个错误。不确定从哪里开始,我是从模型本身还是从Controller检查,还是在视图中添加检查?

2 个答案:

答案 0 :(得分:0)

我敢打赌,当你渲染一张桌子时,你会使用一些想法:

project.client.name

在这种情况下,它应该抛出异常,因为客户端不存在,但您尝试访问name属性。您应该在渲染此表时检查客户端是否存在。

答案 1 :(得分:0)

你可以apply constraint to eager loading。为了概念证明,

$users = Project::with(array('client' => function($query)
{
  $query->raw(
   /*Add your constraint here to coalesce a default for cid or clients.
     You may set a default null record in the client table for this case.*/
  );

}))->get();