2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
目前用戶是主要實(shí)體,因此帖子的排序?qū)⒃谠撚脩舻奶又羞M(jìn)行,而不是在所有帖子中全局排序。我猜您想進(jìn)行全局排序,這意味著帖子應(yīng)該按日期排序
試試這個(gè)在用戶類中添加一個(gè)新關(guān)系
class User extends Model {
public function rpost() {
return $this->belongsTo(\where\ever\posts::class, 'user_id', 'id');
//inverse mapping from user --> posts table
//assuming posts table is using user_id column to track the ownership
//and user table has id as it's primary key
}
}
然后修改你的代碼
User::with('rpost')
->select('posts.title'.'posts.id', 'users.name',
\DB::raw('(SELECT posts.date FROM posts WHERE user.id = posts.user_id ) as sort'))
->where('last_name', 'like', $search['lastname'] . '%')
->where('first_name', 'like', $search['firstname'] . '%')
->where('email', 'like', '%' . $search['email'] . '%')
->whereHas('posts', function ($query) use ($search) {
$query->where('reference', 'like', $search['reference'] . '%');
})
->orderBy('sort')
->paginate(15);

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以使用 sortBy
$users = User::with('posts')->get()
->sortBy(function($user) {
return $user->posts->created_at;
})
或者您可以將這樣的連接與 orderBy 一起使用
$query = User::where('last_name', 'like', $search['lastname'] . '%')->where(
'first_name',
'like',
$search['firstname'] . '%'
)->where('customers.email', 'like', '%' . $search['email'] . '%');
$query = $query->join('posts', 'posts.user_id','=','users.id');
$query = $query->select('posts*','users.*');
$query = $query->orderBy('posts.created_at','asc');
$record = $query->get();
- 2 回答
- 0 關(guān)注
- 333 瀏覽
添加回答
舉報(bào)