Laravel Eloquent,加入并不是预期的结果

时间:2017-10-25 18:56:08

标签: laravel laravel-5 eloquent

我有这样一个雄辩的问题:

    $entity= Entity::find($entity_id)
        ->join('address', 'entities.id', '=', 'address.entity_id');
    dd($entity);

现在我去url / entities / 243

我从:: find得到结果但是我没有从我的 - > gt加入得到结果,所以没有地址。

当我执行此查询时:

    $entity= Entity::where('id', $entity_id)
        ->join('address', 'entities.id', '=', 'address.entity_id')
        ->first();
  

SQLSTATE [23000]:完整性约束违规:1052 where子句中的列'id'不明确(SQL {select * from entities address entities id address }} = entity_idid其中entities = 50和deleted_at +"id": 43 +"name": "Costa Coffee Town Hall" +"type": "Food & Drink" +"tags": "Coffee, Cake, Food" +"email": "cos@liveandnow.com" +"logo": "https://s3.eu-west-2.amazonaws.com/liveandnow-production/public/logo/1502795867.png" +"cover": "" +"bio": null +"main": null +"twitter_business": null +"facebook_business": null +"instagram_business": null +"google_places": null +"eventbrite": null +"featured": 1 +"ical": null +"slug": null +"url": null +"video": null +"api_key": null +"contact_number": null +"contact_name": null +"geoloc_id": 142 +"deleted_at": null +"created_at": "2017-07-27 16:08:12" +"updated_at": "2017-08-15 10:17:31" +"wikipedia": null +"building_name": "The Old Town Hall" +"address": "Parliament Square Greaves Street" +"town": "Oldham" +"postcode": "OL1 1QN" +"telephone": "0161 926 7706" +"private": 0 +"entity_id": 142 为空限制1)

这就是我得到的,我将如何正确构建此查询?所以我想返回匹配的实体,即它的地址,都在原始数组中,我不希望它分开,即

我想要dd($ entity);给我:

实体字段:值 地址字段:值

所以我不必去$ entity->地址来解决问题,希望这是有道理的。

编辑::

//

<div> {{object1.some_property.[get.value.from.your.other.object.and.put.it.in.square.brackets.like.this.as.thats.associative.arrays.notation.which.you.can.use.for.any.object.property]}} </div>

3 个答案:

答案 0 :(得分:1)

使用find()方法的查询应如下所示:

$entity= Entity::leftJoin('address', 'entities.id', '=', 'address.entity_id')
               ->find($entity_id);

使用first()方法的查询应如下所示:

$entity= Entity::where('entities.id', $entity_id)
               ->leftJoin('address', 'entities.id', '=', 'address.entity_id')
               ->first();

答案 1 :(得分:0)

在where子句中使用entities.id而不是id

答案 2 :(得分:0)

您应该使用DB。试试这个:

 $entity= \DB::table('entities')
            ->where('entities.id', $entity_id)
            ->join('address', 'entities.id', '=', 'address.entity_id')
            ->first();