【发布时间】:2014-01-22 16:02:31
【问题描述】:
MySQL 表: 帖子 标签 post_tag(包含 post_id 和 tag_id 列)
// Post.php model
class Post extends Eloquent {
protected $table = 'posts';
public $timestamps = true;
protected $guarded = ['id'];
public function tags()
{
return $this->belongsToMany('Tag');
}
}
// Tag.php model
class Tag extends Eloquent {
protected $table = 'tags';
public $timestamps = false;
protected $guarded = ['id'];
public function posts()
{
return $this->belongsToMany('Post');
}
}
// on routes.php
Route::get('/', function()
{
$post = Post::find(44);
echo $post . '<br>';
$tag = Tag::find(28);
echo $tag;
return $post->tags;
});
当点击 / 时,它会打印 post:44,它会打印 tag:28 并给出
ErrorException 不能将标量值用作数组
访问 Post.php tags() 函数上的 tags 属性时。 请记住,在 post_tag 的表上有一个 post_id=44 和 tag_id=28 的条目,但它可能是空的。 Laravel/php 在尝试访问 belongsToMany('Tag') 方法时给了我这个错误。
我做错了什么?
【问题讨论】:
-
我一直在进一步研究框架代码中的问题,发现如果我改正这样的关系,它可以工作: public function tags() { return $this->belongsToMany('Tag ',null,null,null,'这里的任何东西-not-null'); }
-
嘿,HHVM 准备好迎接黄金时段了吗?
标签: php mysql laravel many-to-many relationships