Php Laravel 5 M2M多态关系未设置?
以下是基本代码:Php Laravel 5 M2M多态关系未设置?,php,laravel,laravel-5,eloquent,polymorphic-associations,Php,Laravel,Laravel 5,Eloquent,Polymorphic Associations,以下是基本代码: /** * Post.php */ class Post extends Illuminate\Database\Eloquent\Model { public function tags() { return $this->morphToMany('Tag', 'taggable', 'taggable_taggables') ->withTimestamps(); } } /** * Tag.php
/**
* 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);
到目前为止还不错。正在透视表中创建关系。但是,如果我立即这样做:
dd($post->tags);
它返回一个空集合attach()
似乎在数据库中创建了关系,但不在模型的当前实例中创建
这可以通过再次加载模型进行检查:
$post = Post::find(1);
dd($post->tags);
现在,这段关系变得更加融洽了
我很确定这在Laravel4.2中是有效的——也就是说,关系在
attach()
之后立即更新。是否有任何方法可以推动Laravel 5执行相同的操作?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);
attach
方法以执行所需的逻辑。然后,创建一个新的模型类来扩展雄辩的模型类,并重写belongToMany
方法来创建新关系类的实例。最后,更新Post模型以扩展新的模型类,而不是雄辩的模型类我现在不太确定这在Laravel 4.2中是否有效。但我仍然想知道是否可以推动Laravel(4.2和/或5)这样做。谢谢你的详细解释。事实上,我是在附加之前加载标签的,这可以解释为什么在强制重新加载之前我看不到标签。最后,我按照您第一个建议中的建议做了:在附加后手动运行
->load('tags')
。