Laravel Eloquent:寻找缺少关系的对象

时间:2015-09-02 18:44:21

标签: php laravel eloquent

我有一个Posts对象,可能有也可能没有Link个对象(Link属于Post和Post hasOne Link)。

我正在尝试查找在某个日期之后创建的帖子,这些帖子尚未创建链接。

我有以下但不起作用:

$posts = Post::where('post_date', '>', 'xxxx')->whereIsNull('link.id'); // which is how I would write it with an OUTER JOIN.

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

使用Laravel eager loading并循环搜索结果以查找没有链接的帖子。

$posts = Post::with('link') -> get();
// loop with foreach and extract posts with no links
$not_linked_posts = array();
foreach ($posts as $k => $post){
  // if link is not set
  if (!isset($post -> link)){
       // add it to array
       $not_linked_posts[$k] = $post -> toArray(); //convert post to array
  }
}

希望这有帮助。