Laravel Eloquent - 动态 属性
Laravel Eloquent - Dynamic property
我还在玩 laravel。目前我想 "minimize" 查询 activity。有没有办法自动更新关系的动态属性(抱歉,不知道怎么命名)?
我认为以下虚拟代码有助于理解我的问题:) 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?
如果有人能给我一些提示,我会很高兴:)
谢谢大家!
在 hasOne
/hasMany
,您调用 save()
关系。在 belongsTo
上,您调用 attach()
关系,然后 save()
父对象。
// hasOne / hasMany
$user->posts()->save($post);
// belongsTo
$post->user()->attach($user);
$post->save();
至于你的问题的其余部分,请阅读关于 this github issue 的讨论,了解为什么你需要重新加载关系。
基本思路是您的关系可以有额外的 where
约束或 order
条款。因此,您不能只将新相关的记录添加到加载的关系集合中,因为没有简单的方法来确定该记录是否属于集合,或者它应该在集合中的什么位置。
如果你想确保你的关系属性包含新的相关记录,你需要重新加载关系。
// 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);
我还在玩 laravel。目前我想 "minimize" 查询 activity。有没有办法自动更新关系的动态属性(抱歉,不知道怎么命名)? 我认为以下虚拟代码有助于理解我的问题:) 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?
如果有人能给我一些提示,我会很高兴:) 谢谢大家!
在 hasOne
/hasMany
,您调用 save()
关系。在 belongsTo
上,您调用 attach()
关系,然后 save()
父对象。
// hasOne / hasMany
$user->posts()->save($post);
// belongsTo
$post->user()->attach($user);
$post->save();
至于你的问题的其余部分,请阅读关于 this github issue 的讨论,了解为什么你需要重新加载关系。
基本思路是您的关系可以有额外的 where
约束或 order
条款。因此,您不能只将新相关的记录添加到加载的关系集合中,因为没有简单的方法来确定该记录是否属于集合,或者它应该在集合中的什么位置。
如果你想确保你的关系属性包含新的相关记录,你需要重新加载关系。
// 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);