Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 using pivot table with hasMany relationship

I'm making a poll system and I have two tables :

  • polls table : Has those fields (id,question,created_at,updated_at).

  • choices table : Has those fields (id,poll_id,choice).

And a pivot table named choice_poll : Has those fields (id,choice_id,poll_id,ip,name,phone, comment ,created_at,updated_at)

Poll Model :

class Poll extends Model 
{

    protected $table = 'polls';
    protected $fillable = ['question'];
    public $timestamps = true;

    public function choices()
    {
      return $this->BelongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
    }
}

Choice Model :

class Choice extends Model 
{

    protected $table = 'choices';
    protected $fillable = ['poll_id','choice'];
    public $timestamps = false;

    public function poll()
    {
      return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
    }
}

Now when I try to build this query it doesn't return the choices :

$poll->first()->choices()->get()

PS: There is many choices in the choices table associated with the first poll.

like image 736
Hamza AlQabali Avatar asked Jul 23 '16 22:07

Hamza AlQabali


Video Answer


1 Answers

In this case you have Many To Many relationship so try to change belongsTo in :

public function poll()
{
    return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
}

To belongsToMany, and it will be :

public function poll()
{
    return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
}

NOTE 1: You have to change BelongsToMany to belongsToMany note the B should be in lower case.

NOTE 2: You want the pivot table with timestapms create_at,updated_at as you mentioned in th OP so you have to use withTimestamps(); :

return $this->belongsToMany('App\Poll')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();

//AND in the other side also

return $this->belongsToMany('App\Choice')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();

Hope this helps.

like image 78
Zakaria Acharki Avatar answered Oct 25 '22 23:10

Zakaria Acharki