Laravel LeftJoin从第一列返回重复值(mysql)

时间:2018-08-24 15:39:33

标签: mysql laravel left-join

专栏工作者: enter image description here

列建议: enter image description here

我的查询:

$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"}

我两次返回了idname和表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');
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是load flex关系:

recommendations

,然后通过遍历建议的方式访问建议,例如

$workers = Worker::with('recommendations')->get();

但是,如果您希望像问题中的示例一样对行进行格式化,则可以利用它们是collections的事实:

@foreach($workers as $worker)

    @foreach($worker->recommendations as $recommendation)

        //

    @endforeach

@endforeach