1
votes

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?

2
I've been further researching the problem into the framework's code an found that if I instead right the relation like this, it works: public function tags() { return $this->belongsToMany('Tag', null, null, null, 'anything-in-here-not-null'); } - mwm
Hey, is HHVM ready for prime time yet ? - Ali Gajani

2 Answers

2
votes
0
votes

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