0
votes

I got 2 models. File model:

class File extends Model
{
    public function user()
    {
        return $this->belongsTo('App\m_user', 'CODUSER');
    }

}

And m_user model:

class m_user extends Model
{
    protected $table = 'm_users';

    public function file()
    {
        return $this->hasMany('App\File', 'id_user');
    } 
}

The tables are the follow:

Files:
id, id_user, name

m_user:
CODUSER, email

I want to get the files with each user. I try with this code and dont return the values of m_user, returns only the values of file:

$file= File::with(['user'])->first();
print_r($file);

The result is:

(...)

[original:protected] => Array
(
[id] => 79
[id_user] => 1
[name] => Sublime Text Build 3211 x64 Setup.exe
)

(...)

[relations:protected] => Array
(
[user] =>
)

The relations are in blank! I need to get the user data in the relations.

UPDATE: i fix the problem using hasOne instead of belongsTo in the File model.

1
It's there, but you have to access with $file->user->email (note: you'll get an error if there's no m_user associated with file.) Also, please name your model correctly; MUser, not m_user, and App\file is App\File - Tim Lewis
Clarify me, do you want the files associated with the user right? - Pedro Costa
@TimLewis i try with the changes that you say and the problem persists - jdoe1980
@PedroCosta Right, that is what i want. - jdoe1980
What problem? You don't really say what the issue is. What is the specific error you're getting? And what code is generating that error? Please edit your question with that information. - Tim Lewis

1 Answers

0
votes

Seeing the clarification provided by you in comments I think you are doing the relations backwards. To see the files that user is associated with you have to:

$user = m_user::findOrFail([user_id]);

$files = $user->file;

Tip: You user model is not created with the best practices, should be MUser.

Hope that helped