Anonymous Anonymous - 1 year ago 50
PHP Question

Model id is overridden by related model

I have an Eloquent model that has a scope method to filter some rows:

class TODocs extends \Eloquent {
public function scopeUnexported($query)
{
$query
->join('to_requests', function ($join) {
$join->on('to_requests.id', '=', 'to_docs.request_id');
$join->whereNull('to_requests.deleted_at');
})
->where('to_docs.export_allowed', true)
->whereNotNull('to_docs.filename')
->whereNull('to_docs.exported_at');

return $query;
}
}


But when I get result for that scope all objects have id that is id from
to_requests
table.

For instance, if I try to get a row from
to_docs
table that has
id = 1
and this row has a foreign key
to_docs.request_id = 2
then the id for the model I get is also 2. However, when I remove a
join
section from scope method than everything works like a charm,
id
is 1

I probably could get rid of
join
but I need this condition to get rows which foreign record has
to_requests.deleted_at IS NULL


Is there a way to fix this method?

Answer

I finally solve this issue. I knew that the problem was in join; however, I couldn't remove it because I need to refer field value in joined table. So I add \Illuminate\Database\Query\Builder::select to fetch only fields from main table

public function scopeUnexported($query)
{
    $query
        ->select('to_docs.*')
        ->join('to_requests', function ($join) {
            $join->on('to_requests.id', '=', 'to_docs.request_id');
            $join->whereNull('to_requests.deleted_at');
        })
        ->where('to_docs.export_allowed', true)
        ->whereNotNull('to_docs.filename')
        ->whereNull('to_docs.exported_at');

    return $query;
}