Ɛɔıs3
Ɛɔıs3

Reputation: 7853

Laravel Eloquent Several relationships

I have three models that I made simple for the example (a user make a request to get a phone) :

  1. User

    • id
    • login
  2. Request

    • id
    • user_id
    • phone_id
  3. Phone

    • id
    • name

The relations are below :

In User model :

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

In Phone model :

public function phoneRequests()
{
    return $this->belongsTo('App\Requests');
    // But it returns null
}

I need to get a collection where I start from the User model and I get all the requested phones (I need there name). The problem is that phone_id is in Requests Model and in the documentation this is inverse.

I can not find any relationship to reach my goal.

The ideal would be to go through the following relation :

Auth::user()->requests->phoneRequests
// Would returns the phone name the user has requested

I also tried to do it with a raw SQL query but I'd rather using relationships. How to do this ?

Upvotes: 1

Views: 328

Answers (2)

Ɛɔıs3
Ɛɔıs3

Reputation: 7853

Thanks to newUserName02's comment, the solution for my question is :

/**
 * Returns all requests made by this client
 * @return Collection
 */
public function requests()
{
    return $this->hasMany('App\Requests');
}

/**
 * Returns all the phones requested by the client
 * @return Collection
 */
public function phones()
{
    return $this->belongsToMany('App\Phone', 'phone_request');
    // where phone_request is the name of the pivot table (App\Requests)
}

Also, I invite you to consult this excellent article (in French) which explains well the relations with schemas.

Upvotes: 0

nakov
nakov

Reputation: 14248

You should have in your Requests model a phone relationship, like this:

public function phone()
{
    return $this->belongsTo('App\Phone');
}

So now you can get all the requests with the phone for the user like so:

$user->requests->first()->phone; // this is for the first request, but you can get the phone for each request in a loop, I guess you know how to do that.

And also note that your relationship in the Phone model is wrong hence the reason for getting null. That one should be again hasMany as in the User because a Phone can have many requests as per your table structure.

In your Phone model you should have this:

public function requests()
{
    return $this->hasMany('App\Requests', 'phone_id');
}

Because a phone can belong to many requests as per your DB structure.

Upvotes: 1

Related Questions