Laravel - 使用Eloquent

时间:2016-10-17 10:05:36

标签: php laravel eloquent

我有两张桌子

1-项目 2-客户

我需要从项目表中获取客户端表中的名称和项目名称

我的Projects类有

public function projectClient()
    {
        return $this->hasMany('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

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

更新

as @Mahfuzul Alam和@WebKenth建议我这样做

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

但那里还有一些错误

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

2 个答案:

答案 0 :(得分:1)

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

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

至于你的问题,你没有引用客户端上的Project对象,你有关系,所以对$clt->projects的简单调用将返回每个$ clt上的Project对象

答案 1 :(得分:0)

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