我的查询:
$getRecommendationWorker = Worker::select('workers.id', 'workers.name', 'workers.photo', 'workers.description', 'workers.profile_worker', 'recommendations.recommendation', 'recommendations.author', 'recommendations.work_author', 'recommendations.profile_author')
->leftJoin('recommendations', 'workers.id', '=', 'recommendations.worker_id')
->get();
Laravel返回:
{"id":5,"name":"Piotr Debowski","photo":"3c29641e2a.jpeg","description":"sdasdasd","profile_worker":"https:\/\/codepen.io\/","recommendation":"pierwsza rekomendacja","author":"Jan Kowalski","work_author":"IT spec","profile_author":"https:\/\/stackoverflow.com\/questions\/43136250\/eloquent-join-table-with-two-conditions"}
{"id":5,"name":"Piotr Debowski","photo":"3c29641e2a.jpeg","description":"sdasdasd","profile_worker":"https:\/\/codepen.io\/","recommendation":"druga rekomendacja","author":"Jan Wo\u017aniak","work_author":"dsad","profile_author":"https:\/\/nczas.com\/2018\/08\/21\/wreszcie-zatrzymali-t"}
我两次返回了id
,name
和表workers
中的其他值。
我想要退货看起来像这样:
{"id":5,"name":"Piotr Debowski","photo":"3c29641e2a.jpeg","description":"sdasdasd","profile_worker":"https:\/\/codepen.io\/","recommendation":"pierwsza rekomendacja","author":"Jan Kowalski","work_author":"IT spec","profile_author":"https:\/\/stackoverflow.com\/questions\/43136250\/eloquent-join-table-with-two-conditions","recommendation":"druga rekomendacja","author":"Jan Wo\u017aniak","work_author":"dsad","profile_author":"https:\/\/nczas.com\/2018\/08\/21\/wreszcie-zatrzymali-t"}
我要从表workers
中仅返回一行,并从表recommendations
中返回与第一个表相关的所有记录。
当我使用groupBy
(例如:...->->groupBy('workers.id')
)时,仅返回表recommendations
中的第一条记录。我不能使用where
,因为所有值都将显示在同一页面上。
列worker_id
与表workers
编辑:
工人模型:
public function recommendations()
{
return $this->hasMany('App\Recommendation');
}
推荐模式:
public function workers()
{
return $this->belongsTo('App\Worker');
}
答案 0 :(得分:1)
最简单的方法是load flex
关系:
recommendations
,然后通过遍历建议的方式访问建议,例如
$workers = Worker::with('recommendations')->get();
但是,如果您希望像问题中的示例一样对行进行格式化,则可以利用它们是collections的事实:
@foreach($workers as $worker)
@foreach($worker->recommendations as $recommendation)
//
@endforeach
@endforeach