这是基本代码:
/**
* 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 做同样的事情?
最佳答案
Laravel 只会加载关系属性一次,无论是急切加载还是延迟加载。这意味着一旦加载了属性,关系的任何更改都不会由属性反射(reflect),除非显式重新加载关系。
您发布的确切代码应该按预期工作,所以我假设有一个片段丢失了。例如:
$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 自动刷新关系。我也想不出您可以 Hook 的模型事件,因为您实际上并未更新父模型。我能想到的主要选项有以下三个:
在模型上创建一个执行附加和重新加载的方法。
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 类。只要确保在需要时始终重新加载您的关系即可。
关于php - Laravel 5 M2M 多态关系未设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576155/