0

Let's say I have User Model. Each User has Pet model.

both have relationship setup correctly.

When I get the user data along with his pets, I do this:

return $this->with('pets');

but what if I want to return the pet name only with the user data? I've been trying that:

return $this->with('pets.name');

Didn't work for me.

2 Answers 2

1

Model

 Class User extends Model ()
 {         
          ...
          public function pets()
           {
              return $this->hasOne('App\Model\Pet');
           }
 }

Controller or Repository or any other object

  function getUserDetails (Request $request) 
   {
         $userId = $request->get('id');
        $findUserById = User::find($userId);
        $fullName = $findUserById->pets->fullname;
   }
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this way :

$users_with_pet_name = DB::table('users')
        ->join('pets', 'users.id', '=', 'pets.user_id')
        ->select('users.*', 'pets.name')
        ->get();

Check out joins section: https://laravel.com/docs/5.1/queries#joins

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.