Repox
Repox

Reputation: 15474

Querying relational table

I have three tables.

tasks

| id | title| 
|----+------|
| 1  | Blah |
| 2  | Blah |
| 3  | Blah |


tags

| id | tag    | 
|----+--------|
| 1  | house  |
| 2  | garden |
| 3  | bath   |


task_tags

| id | task_id | tag_id | 
|----+---------|--------|
| 1  | 1       | 1      |
| 2  | 1       | 3      |
| 3  | 2       | 1      |

I'd like to solve via Eloquent to get to present the tag names from my task model. I tried using hasManyThrough, but without luck. I only got the first result.

Upvotes: 0

Views: 77

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Your pivot table doesn't follow Laravel naming convention (which would be tag_task in this situation) so you need to specify table name in the relation definition like this:

class Task extends \Eloquent {

    public function tags(){
        return $this->belongsToMany('Tag', 'task_tags');
    }
}

Foreign key names are ok, so Eloquent will know them. Printing results in a foreach loop like suggested by @Razor.

Upvotes: 0

Razor
Razor

Reputation: 9855

class Task extends Eloquent {
    public function tags(){
        return $this->belongsToMany('Tag');
    }
}

Then you can do:

$tasks= Task::with('tags')->get();
foreach ($tasks as $task) {
    foreach($task->tags as tag)
        echo $tag->name;
}

For more information, please check many-to-many relations

Upvotes: 3

Related Questions