douhuo3696 2016-10-17 10:05
浏览 50
已采纳

Laravel - 使用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

  • 写回答

2条回答 默认 最新

  • dongyanling9248 2016-10-17 10:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)