vendredi 30 juillet 2021

Relationship eloquent in laravel?

In user :

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

In post

    public function users()
    {
        return $this->belongsTo(Users::class);
    }

I handle in controller :

$user = Users::find('1')->posts;

Then I get an array. And the result returned is exactly what I need


But when I query this way, the result is an empty array. What did I do wrong? Because I need to get a lot of data.

In UserController.php

$listUser = Users::with('posts')->select('name', 'title')
            ->where('type', 1)
            ->get(); // It returns posts as an empty array

Please give me any comments. Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire