Burgi
Burgi

Reputation: 434

Eloquent Removing Columns

I'm having a really strange issue with my eloquent query. I have a table called Calls which I am joining to Contacts and Companies. I am trying to reference the column calls.id but it has been replaced with the id for Companies.

Here is my query:

$calls=DB::table('calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;

I have seen on Github that this seems to be a known bug but no-one has put forward a workaround.

Can anyone point me in the right direction?

Upvotes: 0

Views: 63

Answers (1)

Alex Harris
Alex Harris

Reputation: 6392

The most direction solution to your immediate question is to add a select to your Eloquent query:

$calls=DB::select('calls.* from calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;

Instead of the default select *, explicitly dictate what is returned. However, this can be done a lot more cleanly with Eloquent using models:

Calls::whereHas('companies', function (Builder $query) {
    $query->where('completed', false);
})->orderBy('call_on', 'asc')->get();

In order for this to work you need to setup the relationship on the model level:

// App\Calls model:
public function companies() {
    return $this->belongsTo(App\Companies::class);
}

// App\Companies model:
public function calls() {
    return $this->hasMany(App\Calls::class);
}

Upvotes: 1

Related Questions