亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Laravel 中的 with() 之后的另一個模型中的 OrderBy

在 Laravel 中的 with() 之后的另一個模型中的 OrderBy

PHP
慕工程0101907 2022-11-12 13:24:45
我有一個問題,我正在嘗試按鏈接表中的日期對請求進行排序。我在一對多中有一個名為 User 的表和另一個名為 Posts 的表。User::with('posts')    ->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('date', 'asc');    })    ->orderBy('posts.date', 'desc')    ->paginate(15);我怎樣才能做到這一點 ?
查看完整描述

2 回答

?
慕虎7371278

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);


查看完整回答
反對 回復 2022-11-12
?
智慧大石

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();


查看完整回答
反對 回復 2022-11-12
  • 2 回答
  • 0 關注
  • 323 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號