2017-07-01 50 views
0

我想提出一个查询,我想检查我已经建立了这样的关系:Laravel制约预先加载不工作

内容模型:

public function contentType() 
{ 
    return $this->belongsTo('App\ContentType', 'ct_id'); 
} 

的ContentType

public function contents() 
{ 
    return $this->hasMany('App\Content', 'ct_id'); 
} 

然后,我试图做这样的查询:

$content = Content::where('slug', $arguments['slug']) 
       ->with(['contentType' => function ($query) { 
        $query->where('slug', 'post'); 
       }])->get(); 

return $content; 

我想从Db那里得到$content,它有slug postcontentType,我从表中获得内容,但是在测试它后,我每次都得到相同的记录,无论我把它作为slugcontentType。我在Db中只有一条记录,这就是为什么我得到相同的记录,但我甚至应该得到那个,如果它没有contentType有一个slug不同于post。我究竟做错了什么?

+0

我完全不理解你的问题,你从表内容中检索一条记录,并在contentType表中有一条关联的记录。你总是获得contentType的相同记录? –

+0

我总是从内容表中获取相同的记录,无论我将ContentType – Leff

回答

1

我能够实现我想whereHas查询:

$content = Content::whereHas('contentType', function ($query) { 
        $query->whereIn('slug', ['post', 'page']); 
       }) 
       ->where('slug', $arguments['slug']) 
       ->with('supplementary') 
       ->first(); 

这样,我只取有POST或页面作为contentType关系的蛞蝓内容。