guidsen
guidsen

Reputation: 2403

Grab relation of saved Eloquent model

After I save a Eloquent model, how am I able to retrieve a relationship with it?

So for example:

$model = new Foo;
$model->save();
dd($model); //return an object of Foo

Let's say I've set an relation to Baz, I should grab the relation like a normal Eloquent Object.

dd($model->with('baz')->get());

But this is returning every Foo record in de database with the relationship.

I just want to be able to get the current Baz model which is related to the saved Foo model.

I could do:

$result = Foo::with('baz')->find($model->id);
dd($result);

But this results in another query, which I want to prevent.

Upvotes: 3

Views: 1053

Answers (3)

lukasgeiter
lukasgeiter

Reputation: 152900

Simply just access it once like this:

$model->baz

And the relationship will be loaded.

Alternatively you can lazy eager load the relation:

$model->load('baz'); 

The effect is the same, although the first way allows you to actually use the result of the relation directly. If you just want to have the relationship in your array / JSON output I suggest you use the second method, because it's clearer what you're doing.

Upvotes: 2

user1669496
user1669496

Reputation: 33078

You should eager load on existing models using load().

Try

$model = new Foo;
$model->save();
$model->load('baz');

Upvotes: 0

Edgar Orozco
Edgar Orozco

Reputation: 2782

Depends on how you declare your relationships on your models. Assuming your relationship is declared as One to Many like this:

class Foo extends Eloquent {
    public function bazes()
    {
        return $this->hasMany('Baz');
    }
}

Then you can try this:

$results = $model->bazes;

or

$results = Foo::find($id)->bazes

$results is an iterable collection of bazes related directly with foo->id = x

But if you want eager loading with filters, then you can try like this:

$result = Foo::with(array('bazes' => function($query)
{
    $query->where('id', $id);

}))->get();

I hope this works for you.

Upvotes: 0

Related Questions