2 回答

TA貢獻1802條經驗 獲得超4個贊
目前用戶是主要實體,因此帖子的排序將在該用戶的帖子中進行,而不是在所有帖子中全局排序。我猜您想進行全局排序,這意味著帖子應該按日期排序
試試這個在用戶類中添加一個新關系
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貢獻1946條經驗 獲得超3個贊
您可以使用 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 關注
- 323 瀏覽
添加回答
舉報