2016-10-10 108 views
0

我試過下面的文檔here,但沒有得到期望的結果的所有記錄, 我的表看起來像檢索與laravel雄辯

用戶表

id (pk - int) | username, 

鳴叫表

id (pk - int) | user_id (fk - int) | tweet(varchar) 

用戶型號

public function tweets() { 
    return $this->hasMany('App\Tweet', 'user_id); // user_id is FK 
} 

資料Tweet模型

public function user() { 
    return $this->belongsTo('App\User'); 
} 

而且在控制器側,我'使用口才來檢索數據。我有這樣的方法,

public function ajax($id) { 
    $data = User::with('tweets')->find($id)->tweets(); 
    return $data; 
} 

我試過邏輯here以下,但我發現在控制器代碼以下錯誤:

試圖讓非對象的屬性

+1

做一個'dd(User :: with('tweets') - > find($ id))''。這將最有可能返回null,從而導致錯誤。您需要確保用戶表上存在'$ id' –

+0

使用'with()'急切地加載推文。除非你明確地尋找關係,否則你應該使用'find($ id) - > tweets'而不是'tweets()'(注意缺少括號)。前者獲取數據,後者獲得關係。 –

+1

嘗試'$ data = User :: with('tweets') - > find($ id) - > tweets;'insteadof'$ data = User :: with('tweets') - > find($ id) - >鳴叫();'。 –

回答

1

爲什麼就不能做到像:

$User = User::find($id); 
$tweets = Tweet::whereUserId($id)->get(); // or ->paginate(20); 
return compact('User', 'tweets'); 

附:我知道急切的加載,但它做了相同的操作+它也做了額外的但不必要的操作加入tweets收集到User對象。

+0

可以請你簡單介紹一下如何使用whereUserId()方法嗎? –

+0

whereUserId($ id)與where('user_id',$ id)相同它是PHP中的魔術方法,當您編寫whereSomethinElse($ var)時,它將使用它來轉換爲where('something_else',$ var) – num8er

0

嘗試使用->get();來獲取所有記錄。