Tuxman
Tuxman

Reputation: 398

Problem using Eager Loading in a Eloquent Model

I have 2 models and their relations. The first class is called 'Documento':

class Documento extends Model
{
    protected $table = 'documento';
    protected $primaryKey = 'cod_documento';

    public function emisor()
    {
        return $this->belongsTo('App\Emisor', 'cod_emisor', 'cod_emisor');
    }
}

The second one is called 'Emisor':

class Emisor extends Model
{
    protected $table = 'emisor';
    protected $primaryKey = 'cod_emisor';

    public function documentos()
    {
        return $this->hasMany('App\Documento', 'cod_emisor', 'cod_emisor');
    }
}

The models relationship is one-to-many (one emisor has many documents, and one document has only one emisor).

In Thinker, i tryo to get a emisor from a document and this work well:

>>> Documento::find(1)->emisor->name
=> "Emisor Name"

But when I try to do Eager Loading the emisor in document, that "fails":

>>> Documento::find(1)->with('emisor')->count();
=> 94041

I expected one result, but the query return 94041 documents.

Why is this happening? How to obtain a one document with nested emisor?

Upvotes: 0

Views: 605

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Swap find() and with():

$documento = Documento::with('emisor')->find(1);

Or use lazy eager loading:

$documento = Documento::find(1)->load('emisor');

With an existing model instance:

$documento->load('emisor');

You are getting this unexpected result because Documento::find(1)->with('emisor') creates a new query that queries all Documento entries. Hence the total count of 94041.

Upvotes: 1

Related Questions