【发布时间】:2015-02-18 04:45:01
【问题描述】:
这是基本代码:
/**
* 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 4.2 中是否有效。但我仍然想知道是否可以推动 Laravel(4.2 和/或 5)这样做。
标签: php laravel laravel-5 eloquent polymorphic-associations