簡體   English   中英

Laravel Eloquent-動態屬性

[英]Laravel Eloquent - Dynamic property

我還在和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?

如果有人可以給我一些提示,我將非常高興:)謝謝大家!

hasOne / hasMany ,您可以在關系上調用save() belongsTo ,您可以在關系上調用attach() ,然后save()父級save()

// hasOne / hasMany
$user->posts()->save($post);

// belongsTo
$post->user()->attach($user);
$post->save();

至於其余的問題,請閱讀有關此github問題的討論,以了解為什么需要重新加載關系。

基本思想是,您的關系可以具有其他where約束或order子句。 因此,您不能僅將新相關的記錄添加到已加載的關系Collection中,因為沒有簡單的方法來確定該記錄是否甚至屬於該Collection或應該在Collection中的哪個位置。

如果要確保您的關系屬性包括新相關的記錄,則需要重新加載該關系。

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM