Laravel Eloquent - 动态财产

时间:2016-04-17 15:54:20

标签: php laravel caching eloquent relationship

我还在玩laravel。目前我想“最小化”查询活动。有没有办法自动更新关系的动态属性(抱歉,不知道如何命名)? 我认为以下虚拟代码有助于理解我的问题:) 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?

如果有人能给我一些提示,我会很高兴:) 谢谢你们!

1 个答案:

答案 0 :(得分:2)

hasOne / hasMany,您就此关系致电save()。在belongsTo上,您可以在关系上调用attach(),然后在父母save()上调用。{/ p>

// 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);
相关问题