Reputation: 93
I am still playing around with laravel. At the moment i would like to "minimize" query activity. Is there a way to automatically update the dynamic property of a relationsship (sorry, don't know how to name it)? I think the following dummy code helps to understand my question :) http://laravel.io/bin/mG0Qq
Class User extends Model {
public function posts()
{
return $this->hasMany(Post::class);
}
}
$user = User::fetchSomeUser();
$post = Post::createSomeNewPost();
var_dump($user->posts); // Gives me all the posts which where attached to the user BEFORE i loaded the model from the DB
$user->posts()->attach($post); // or save?
var_dump($user->posts);
// Generates the same output as above. The new attached post is not fetched
// by this dynamic property. Is there a way to get the new post into this dynamic property
// WITHOUT reloading the hole data from the DB?
I would be very happy if someone could give me some tips :) Thank you guys!
Upvotes: 1
Views: 1069
Reputation: 62348
On hasOne
/hasMany
, you call save()
on the relationship. On belongsTo
, you call attach()
on the relationship and then save()
the parent.
// hasOne / hasMany
$user->posts()->save($post);
// belongsTo
$post->user()->attach($user);
$post->save();
As far as the rest of your question, please read the discussion on this github issue for why you need to reload the relationship.
The basic idea is that your relationship could have additional where
constraints or order
clauses. Therefore, you can't just add the newly related record to the loaded relationship Collection because there is no easy way to determine if that record even belongs in the Collection, or where in the Collection it should go.
If you want to ensure your relation attribute includes the newly related record, you need to reload the relationship.
// first call to $user->posts lazy loads data
var_dump($user->posts);
// add a newly related post record
$user->posts()->save($post);
// reload the relationship
$user->load('posts');
// if the newly related record match all the conditions for the relationship,
// it will show up in the reloaded relationship attribute.
var_dump($user->posts);
Upvotes: 2