繁体   English   中英

Laravel-使用Eloquent从两个表中检索所有用户及其项目

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

我有两张桌子

1-项目2-客户

我需要从客户端表中获取名称,并从项目表中获取项目名称

我的专案课程有

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

而我的User类有

    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');
    }

}

在我的客户控制器中

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

现在在我看来

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

如何在此处显示此项目标题?

更新资料

因为@Mahfuzul Alam和@WebKenth建议我这样做

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

但那里还是有问题

在我的数据库中,我有两个用户,而project_id = 1,但在我view ,第一个用户project_id = 1,第二个用户project_id = 2

考虑将projectClient关系重命名为client()

这样,您可以调用$project->client并从项目中接收客户端对象。

对于您的问题,您没有在客户端上引用Project对象,而是具有关系,因此对$clt->projects的简单调用将在每个$ clt上返回Project对象。

考虑到pro_title作为项目标题列,请尝试{{ $clt->project->pro_title }} 如果不起作用,请他们粘贴您的User类的代码,然后让我们看一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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