Help me please with this query.
SELECT d.date, d.id, d.message, u.username
FROM dialogs d JOIN users u ON d.user_id = u.id
AND d.is_deleted = 0
WHERE d.id > ? ORDER BY d.id DESC LIMIT 30
There are messages with authors. Now I'm using DB::select for this query, but want something like:
Dialog::all(['date', 'id', 'message'])
->where('is_deleted', '=', 0)
->with('user')
->idDescending()
->take(30)
->get();
Laravel 4.2
Little adition. Works only if list of selected fields contains both local and foreign keys.
Dialog::with('user') ->where('is_deleted', '=', 0) ->orderBy('id', 'desc') ->take(30) ->get(['date', 'id', 'message', 'user_id']);
public function user() { return $this->belongsTo('User')->select(['username', 'id']); }
If there no keys, user is null.
If you have your relation setup correctly this should be good:
$rows = Dialog::with('user') ->where('is_deleted', '=', 0) ->orderBy('id', 'desc') ->take(30) ->get(['date', 'id', 'message'])
You should be able to access the user with
foreach($rows as $row){ $row->user->username; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.