简体   繁体   中英

Laravel 5.1 Join issue while using Eloquent

Here is my Model Receipe

 public function favorite()
{
    return $this->hasMany('App\ReceipeFavorite');
}

Here i can able to get the

 $userId = 1;
 $favorite = User::find($userId)->favorite;
 return $favorite;

Using this i can able to fetch the record with id user_id in the receipe_favorites table by having this query.

ie, Record matching for all the coloumns with user_id - 1

$favorite = User::find(1)->favorite;
return $favorite;


[{"id":1,"receipe_id":"1","user_id":"1","created_at":"2015-09-15 15:49:12","updated_at":"2015-09-15 15:49:12"},{"id":2,"receipe_id":"2","user_id":"1","created_at":"2015-09-15 15:50:07","updated_at":"2015-09-15 15:50:07"}]

Now, I wanted to get the Receipe Name along with the Result.

Here is my Table Structure

Table

users
->id

receipe
->id

receipe_favorites
->id
->receipe_id
->user_id

Note :

I am trying to get the Receipe Id, Receipe Name if the User Id is passed.

Try the following, I had a similar thing to do:

public function favorite() {
    return $this->belongsToMany('App\Receipe', 'receipe_favorites', 'user_id', 'receipe_id');
}

This is how you define a many-to-many relationship.

Params:

  1. Model
  2. Pivot table
  3. Column to join in current model
  4. Column to join model defined in 1)

See more examples here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM