2017-07-18 19 views
0

我使用this repo作爲我的項目的起點。Laravel 5.4獲取相關數據並顯示

我有一個user表和clubs表。 User可以有一個俱樂部,club連接到一個user

因此,我在下面的clubs表中定義了hasOne關係。

public function user() 
{ 
    return $this->hasOne(User::class, 'id', 'user_id'); 
} 

clubs表有user_id列。

我無法在我的index頁面上獲取正確的數據以顯示UseruserName

我正在使用ClubsRepository來顯示數據。

下面是它的代碼。

public function __invoke(ManageClubRequest $request) 
{ 
    return Datatables::of($this->clubs->getForDataTable()) 
     ->escapeColumns(['clubName', 'sort']) 
     ->addColumn('user', function ($clubs) { 
      return $clubs->user->pluck('first_name'); 
     }) 
     ->addColumn('actions', function ($clubs) { 
      return $clubs->action_buttons; 
     }) 
     ->withTrashed() 
     ->make(true); 
} 

在下面庫是我的 'getFromDataTable()' 方法

public function getForDataTable() 
{ 
    return $this->query() 
     ->with('user') 
     ->select([ 
      'clubs.id', 
      'clubs.clubName', 
      'clubs.description', 
      'clubs.user_id', 
      'clubs.created_at', 
      'clubs.updated_at', 
     ]); 
} 

index.blade代碼如下

<table id="clubs-table" class="table"> 
    <tr> 
     <th>clubName</th> 
     <th>description</th> 
     <th>userName</th> 
     <th>created</th> 
     <th>last_updated</th>   
    </tr> 
</table> 

<script> 
    $(function() { 
     $('#clubs-table').DataTable({ 
      dom: 'lfrtip', 
      processing: false, 
      serverSide: true, 
      autoWidth: false, 
      ajax: { 
       url: '{{ route("admin.access.clubs.get") }}', 
       type: 'post', 
       data: {status: 1, trashed: false}, 
       error: function (xhr, err) { 
        if (err === 'parsererror') 
         console.log(err); 
       } 
      }, 
      columns: [ 
       {data: 'clubName', name: 'clubs.clubName'}, 
       {data: 'description', name: 'clubs.description'}, 
       {data: 'user', name: 'user.first_name', sortable:false}, 
       {data: 'created_at', name: 'clubs.created_at'}, 
       {data: 'updated_at', name: 'clubs.updated_at'} 
      ], 
     }); 
    }); 
</script> 

我到底做錯了什麼?

+0

@AaronFahey試過,但它不起作用。 –

回答

0

試試這個查詢來獲取用戶與他們的俱樂部數據

User::with(array('clubs' => function($q) { 
    }))->get(); 
0

你好像用錯了那種關係 - 如果俱樂部表有一個user_id列,這意味着它belongs to的用戶,而不是它是has one用戶。

假設每個用戶可以擁有多個俱樂部,你想要的是

// in the User model 
public function clubs() 
{ 
    return $this->hasMany(Club::class); 
} 

// in the Clubs model 
public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

另外,我不熟悉的數據表,但有一點值得注意的是,你實際上並不執行在您的getForDataTable()方法中查詢。它缺少->get()或類似的。另外還有一個問題,$this->query()似乎並不是您嘗試做的最有效的方式,但很難說清楚。

而在這行:

return Datatables::of($this->clubs->getForDataTable()) 

是俱樂部多傢俱樂部的集合?因爲您無法在對象集合上調用模型方法。

+0

我試過這個,現在它顯示所有用戶'first_name'作爲數組。 –

+0

我已經更新了一些 - 如果它不起作用,您能否更具體地描述'$ this-> clubs'是什麼,以及您想要調用什麼? –