簡體   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