Laravel Eloquent-动态属性


Laravel Eloquent - Dynamic property

我还在和拉拉威尔玩。目前,我想"最小化"查询活动。有没有一种方法可以自动更新关系的动态属性(对不起,不知道如何命名)?我认为以下伪代码有助于理解我的问题:)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();

至于你的其他问题,请阅读关于github问题的讨论,了解你为什么需要重新加载关系。

基本思想是,您的关系可能有额外的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);