2016-04-17 12 views
1

私はまだlaravelで遊んでいます。現時点では、私はクエリの活動を「最小限に抑えたい」と思います。リレーションシップの動的プロパティを自動的に更新する方法はありますか(申し訳ありませんが、名前を付ける方法はわかりません)。 私は、次のダミーのコードは、誰かが私に は君たちをありがとう:)いくつかのヒントを与えることができれば、私はとても幸せになる私の質問:) http://laravel.io/bin/mG0QqLaravel Eloquent - 動的プロパティ

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? 

を理解するのに役立ちます!だと思います

答えて

2

hasOne/hasManyの場合は、関係にsave()を呼び出します。 belongsToには、関係にattach()、次に親にはsave()が呼び出されます。限り、あなたの質問の他の部分と

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

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

、あなたが関係をリロードする必要がある理由についてthis github issue上の議論をお読みください。

基本的な考え方では、あなたの関係に追加の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); 
+0

ありがとうございました! それは意味があり、私はその問題を理解しています。 ダンプを与えたいですが、十分な評判がありません; edit:$ user-> load( 'posts')も本当にうまくいきません。しかし、私は最終的にそれをテストするのに十分な時間がありません – Leichti