C
C
chelkaz2016-03-08 17:31:56
Laravel
chelkaz, 2016-03-08 17:31:56

Laravel Don't live so hard. Eloquent ORM - One to One?

There is a table of users and a table with their photos.
There are two models. User and Photo_user
In the User model:

public function GetUserPhoto () {
        return $this->hasOne('App\Models\Photo_user');
  }

I output it like this in the template:
echo \App\Models\User::find(Auth::user()->id)->GetUserPhoto->name;

Is it possible to do something like this?
In the User model
public function GetUserPhoto () {
        return Photo_user::where('user_id', $this->id)->first()->name;
  }

And output \App\Models\User::GetUserPhoto(); ?
But it only works on the first option. The second one doesn't work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2016-03-08
@JhaoDa

In the model

public function getPhotoNameAttribite()
{
    return $this->GetUserPhoto->name;
}

, in template
This is written in the documentation - https://laravel.com/docs/5.2/eloquent-mutators#acc...
And in general, your code is terrible. Read the doc.

A
Andrzej Wielski, 2016-03-08
@wielski

Do you even have the slightest understanding of what MVC is?
Are you really displaying THIS in the view?
First, Auth::user()it already contains the User model object. Why get the id from the model and query the database again?
Instantly, the output is reduced to the following form:
Let's go further.
In the User model, we create a relationship CORRECTLY:

public function userPhoto() {
    return $this->hasOne('App\Models\Photo_user'); // Советую называть модели как нормальные люди. UserPhoto - как вариант. Забудьте нижнее подчеркивание, весь Laravel - это CamelCase.
}

In the same place we create the userPhoto attribute:
public function getUserPhotoAttribute(){
     if ( ! array_key_exists('userPhoto', $this->relations))
   $this->load('userPhoto');

     $related = $this->getRelation('userPhoto')->first();

     return ($related) ? $related->name : false; // выводим userPhoto->first()->name
}

Now we can easily use
{{ Auth::user()->userPhoto }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question