【发布时间】:2015-05-12 09:38:27
【问题描述】:
我试图从早上开始进行一个查询工作,但无法让它工作我有两张桌子摄影师和评论请看一下结构,然后我会在底部提出问题:
评论表:
id int(10) unsigned -> primary key
review text
user_id int(10) unsigned foreign key to users table
user_name varchar(64)
photographer_id int(10) unsigned foreign key to photographers table
摄影师表:
id int(10) unsigned -> primary key
name text
brand text
description text
photo text
logo text
featured varchar(255)
摄影师模特:
class Photographer extends Model
{
public function reviews()
{
return $this->hasMany('\App\Review');
}
}
评论模型:
class Review extends Model
{
public function photographers()
{
return $this->belongsTo('\App\Photographer');
}
}
我查询记录的逻辑
$response = Photographer::with(['reviews' => function($q)
{
$q->selectRaw('max(id) as id, review, user_id, user_name, photographer_id');
}])
->where('featured', '=', 'Yes')
->get();
问题是:我想获取评论表中至少有一条评论的所有摄影师,我也想只获取一条最新的评论,我可能有多个摄影师的评论但是我只想要一个。
【问题讨论】:
-
它与这个问题的答案无关,但我会将
Review::photographers方法重命名为 Review::photographer,因为它是“属于”关系,并且只会返回一个结果。 (语义)
标签: eloquent laravel-5 relationship