【问题标题】:laravel order model by querylaravel 通过查询订购模型
【发布时间】:2018-08-31 22:49:40
【问题描述】:

我正在使用 laravel 5.5.40 我正在尝试使用查询来订购这样的模型:

    select * from table1 order by (select nbr from table2 where 
    table2.id=table1.param)

所以我想用我的模型来做这个:

    $content= Model::where(function($query){
    return $query;
    })
    ->orderBy("????", 'asc')            
    ->paginate(10);

在哪里???被查询替换(选择...) 有可能吗?我确实需要分页,这很重要 请帮助我,谢谢

【问题讨论】:

  • 你的 Laravel 版本是什么?
  • 我的版本是 5.5.40。谢谢

标签: laravel model sql-order-by


【解决方案1】:

使用orderByRaw():

$content = Model::orderByRaw('(select nbr from table2 where table2.id=table1.param)')            
    ->paginate(10);

【讨论】:

  • 工作正常,谢谢!然而;我正在使用 $content->user->id,现在它无法显示 Trying to get property of non-object 错误您对此有何看法?
  • 请发布您的查询。 table2是否对应users
【解决方案2】:

试试

$content = Model::orderBy("????", 'asc')->simplePaginate(10);

【讨论】:

  • 感谢您的回答,我可以替换“???”与(从表 2 中选择 id ...)?这就是问题
  • @nacerdjaafri 否。您正在尝试从另一个表的 id 列中排序模型的结果?
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 2012-11-09
  • 2012-01-18
  • 1970-01-01
相关资源
最近更新 更多