首页 文章

多对多(belongsToMany)Laravel关系似乎在HHVM下不起作用

提问于
浏览
1

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;
});

点击/打印后:44,打印标签:28并给出

ErrorException不能将标量值用作数组

当访问Post.php tags()函数上的tags属性时 . 请记住,在post_tag的表上有一个post_id = 44和tag_id = 28的条目,但它可能是空的 . Laravel / php在尝试访问belongsToMany('Tag')方法时给出了这个错误 .

我究竟做错了什么?

2 回答

  • 2

    应该在2月更新时修复:http://www.hhvm.com/blog/3287/hhvm-2-4-0

  • 0

    我相信你需要使用急切加载:

    $post = Post::with('tag')->find(28);
    

    我没有在我面前设置laravel进行测试 . 所以 find 可能不是可链接的,所以你可能需要这样做:

    $post = Post::with(array('tag' => function($query)
    {
        $query->where('id', '=', 44);
    }))->get();
    

相关问题