Question

MySQL tables: posts tags post_tag (with columns post_id and 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;
});

when hitting / it prints post:44, it prints tag:28 and gives

ErrorException Cannot use a scalar value as an array

when accessing tags property that is on Post.php tags() function. bare in mind that on post_tag's table there's an entry with post_id=44 and tag_id=28 but it could be empty. Laravel/php gives me that error while trying to access the belongsToMany('Tag') method.

what am I doing wrong?

Was it helpful?

Solution

Should be fixed on February update: http://www.hhvm.com/blog/3287/hhvm-2-4-0

OTHER TIPS

I believe you need to use eager loading:

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

I don't have a laravel setup in front of me to test. So find might not be chainable, so you might need to do this:

$post = Post::with(array('tag' => function($query)
{
    $query->where('id', '=', 44);
}))->get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top