简体   繁体   中英

Laravel - retrieve all user with their project from two tables using Eloquent

I have two tables

1- projects 2- clients

I need to get the names from the client table and the project name from the projects table

my Projects class has

public function projectClient()
    {
        return $this->hasMany('User');
    }

and my User class has

    class User extends Eloquent implements UserInterface, RemindableInterface
{

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'client';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function project()
    {
        return $this->belongsTo('Projects', 'id');
    }

}

and in my clients controller

$clients = User::with('project')->get();
        //dd($clients);
        return View::make('admin.manageClients.viewClients', compact('clients'));

now in the view I try this

@foreach($clients as $clt)
{{ $clt->first_name }} //work fine
{{ $clt->pro_title }} //didn't show the project title
@endforeach

how can I show this project title here?

Update

as @Mahfuzul Alam and @WebKenth suggest I did it like this

{{ $clt->project->pro_title }}

but something still wrong there

in my database I got two user and the the project_id = 1 but in my view the first user project_id = 1 and the second project_id = 2

consider renaming the projectClient relationship to client()

this way you can call $project->client and receive the client object from the project.

As for your problem, you are not referencing the Project object on the client, you have the relationship so a simple call to $clt->projects will return the Project object on each $clt.

Considering, pro_title as your project title column try {{ $clt->project->pro_title }} . If it don't work, they please paste code of your User class and let us take a look at that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM