user947668
user947668

Reputation: 2728

Laravel selection from pivot table

I have three tables: users, items and user_items. A user has many items and a item belongs to many users.

**Users**
id
username
password

**Items**
id
name

**User_items**
id
user_id
item_id

Models:

class User extends Eloquent {
    public function items()
    {
        return $this->belongsToMany('Item', 'user_items', 'item_id', 'user_id');
    }
}

class Item extends Eloquent {
    public function users()
    {
        return $this->belongsToMany('User', 'user_items', 'user_id', 'item_id');
    }
}

I need to select all items table, print it and highlight rows which belongs to specific user id=1.

enter image description here

Selection highlighted output:

enter image description here

What is the right way to do it (in laravel style)?

Upvotes: 1

Views: 6562

Answers (2)

Diptesh Atha
Diptesh Atha

Reputation: 901

You can do it like this way...

class User extends Eloquent {
    public function items()
    {
        return $this->belongsToMany('Item', 'user_items', 'item_id', 'user_id')->withPivot('id');
    }
}

class Item extends Eloquent {
    public function users()
    {
        return $this->belongsToMany('User', 'user_items', 'user_id', 'item_id')->withPivot('id');
    }
}

From controller..

$user_id = 2;
Item::with(['users'=>function($q) use ($user_id){$q->where('user_id',$user_id);}])->get();

In view at the time of listing a row you can highlight the row just use a condition as each item->users is blank or not.

Upvotes: 1

Satish Shinde
Satish Shinde

Reputation: 2996

You can use it like this

public function user_items()
    {
        return $this->belongsToMany('User', 'user_items', 'user_id', 'item_id')->withPivot('id');
    }

Like this you can access values of third table.

Some useful links- http://www.developed.be/2013/08/30/laravel-4-pivot-table-example-attach-and-detach/ http://vegibit.com/many-to-many-relationships-in-laravel/

http://laravel.com/docs/4.2/eloquent

Upvotes: 1

Related Questions