【问题标题】:Many-to-many (belongsToMany) Laravel relation doesn't seem to work under HHVM多对多(belongsToMany)Laravel 关系似乎在 HHVM 下不起作用
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    我面前没有要测试的 laravel 设置。所以find 可能无法链接,所以你可能需要这样做:

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

    【讨论】:

    • 这是一个 HHVM 问题。这在 Laravel 中是多对多的。应该开箱即用。我忘了我使用的是 hhvm 而不是 php。到目前为止,它碰巧不能与所有东西一起使用。
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 2018-01-03
    • 2021-12-08
    • 1970-01-01
    • 2014-03-09
    • 2017-01-18
    • 1970-01-01
    相关资源
    最近更新 更多