Reputation: 59
I tried to refrain myself from asking a stupid question once again, but here i am...
So i want to check if a ID in my pivot table (tutorial_id) matches another id. However, i have no idea how to to get this ID from the pivot table.. this is what i tried:
Controller:
class TagController extends BaseController {
public function getTutorials($tag) {
$tag_id = Tag::where('name', $tag)->first();
$tutorials = Tutorial::with('tags')->where('tutorial_id', '=', $tag_id->id)->get();
return View::make('tutorials/tags', array(
'tutorials' => $tutorials
));
}
}
Tutorial model:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function tags() {
return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
}
}
Tag model:
class Tag extends Eloquent {
protected $table = 'tags';
public function tutorials() {
return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
}
}
Database looks like this:
However i now get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tutorial_id' in 'where clause' (SQL: select * from `tutorials` where `tutorial_id` = 1)
Upvotes: 1
Views: 100
Reputation: 3012
So you want all tutorials with tag_id->id
, you can do that like this: $tag_id->tutorials
I reformatted the code for you:
public function getTutorials($tag) {
$tag = Tag::where('name', $tag)->first();
return View::make('tutorials/tags', array(
'tutorials' => $tag->tutorials
));
}
reference: http://vegibit.com/many-to-many-relationships-in-laravel/
Upvotes: 1