以下是基本代码:
/**
* Post.php
*/
class Post extends Illuminate\Database\Eloquent\Model {
public function tags() {
return $this->morphToMany('Tag', 'taggable', 'taggable_taggables')
->withTimestamps();
}
}
/**
* Tag.php
*/
class Tag extends Illuminate\Database\Eloquent\Model {
protected $table = 'taggable_tags';
public function taggable() {
return $this->morphTo();
}
}
现在请使用以下代码:
// assume that both of these work (i.e. the models exist)
$post = Post::find(1);
$tag = Tag::find(1);
$post->tags()->attach($tag);
到目前为止一切顺利。正在taggable_taggables
数据透视表中创建关系。但是,如果我马上做:
dd($post->tags);
它返回一个空集合。 attach()
似乎在数据库中创建了关系,但在模型的当前实例中却没有。
可以通过再次加载模型来检查:
$post = Post::find(1);
dd($post->tags);
现在关系充满了水分。
我很确定这在Laravel 4.2中有效 - 即关系在attach()
之后立即更新。无论如何要推动Laravel 5做同样的事情吗?
答案 0 :(得分:2)
Laravel只会加载关系属性一次,无论是急切加载还是延迟加载。这意味着一旦加载了属性,除非明确重新加载关系,否则属性不会反映对关系的任何更改。
您发布的确切代码应该按预期工作,因此我假设有一个缺失的部分。例如:
$post = Post::find(1);
$tag = Tag::find(1);
$post->tags()->attach($tag);
// This should dump the correct data, as this is the first time the
// attribute is being accessed, so it will be lazy loaded right here.
dd($post->tags);
对战:
$post = Post::find(1);
$tag = Tag::find(1);
// access tags attribute here which will lazy load it
var_dump($post->tags);
$post->tags()->attach($tag);
// This will not reflect the change from attach, as the attribute
// was already loaded, and it has not been explicitly reloaded
dd($post->tags);
要解决此问题,如果需要刷新关系属性,可以使用load()
方法,而不是重新检索父对象:
$post = Post::find(1);
$tag = Tag::find(1);
// access tags attribute here which will lazy load it
var_dump($post->tags);
$post->tags()->attach($tag);
// refresh the tags relationship attribute
$post->load('tags');
// This will dump the correct data as the attribute has been
// explicitly reloaded.
dd($post->tags);
据我所知,没有任何参数或设置可以强制Laravel自动刷新关系。我也无法想到你可以加入的模型事件,因为你并没有真正更新父模型。我能想到三个主要选择:
在模型上创建一个执行附加和重新加载的方法。
public function attachTags($tags) {
$this->tags()->attach($tags);
$this->load('tags');
}
$post = Post::find(1);
$tag = Tag::find(1);
$post->attachTags($tag);
dd($post->tags);
创建一个新的关系类,扩展BelongsToMany关系类并覆盖attach
方法以执行所需的逻辑。然后,创建一个扩展Eloquent Model类的新模型类,并覆盖belongsToMany
方法以创建新关系类的实例。最后,更新Post模型以扩展新的Model类,而不是Eloquent Model类。
请确保在需要时始终重新加载您的人际关系。