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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探