![](/img/trans.png)
[英]How can i retrieve table count in a database by using eloquent in Laravel?
[英]How can I retrieve row from another table in Laravel Eloquent?
我有3個表格: posts
, votes
和users
。 我用Eloquent編寫了一個簡潔的代碼,以僅檢索用戶尚未投票的帖子。
$posts = Post::whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();
return response()->json(['posts' => $posts])->withCallback($request->input('callback'));
但我也想從表用戶中檢索用戶名。 我想用json傳遞數據。
如果我嘗試使用查詢生成器來做到這一點,則很難消除用戶已經投票的帖子。
您可以手動連接到用戶表
$posts = Post::join('users', 'users.id', '=', 'posts.user_id')
->whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();
或者,您可以在Post
模型類中定義一個關系 。
public function user()
{
return $this->belongsTo('App\User');
}
然后使用with('user')
從用戶表中檢索數據。
$posts = Post::with('user')
->whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.