laravel-sql

执行原始SQL且分页

$sql = '(SELECT id,title,uid, (`reads`+likes*20+collects*30+comments*10)/POW(UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(release_at),1.2) AS score,`reads`,likes,collects,comments,release_at FROM news  ORDER BY score DESC) as cc';
        
$res = DB::table(DB::raw($sql))->paginate(10);


$sql = '(select id,uid,title from news) cc';

$res = DB::table(DB::raw($sql))->paginate(10);
       
print_r($res->toArray());


自定义排序


NewsModel::orderByRaw("sort=0,sort asc")->get();

关联结果类型

关联一个one 没有数据为null

关联多个many 没有数据为集合对象,count里面的数目是0

关联查询 whereHas 与 orWhereDoesntHave

获取的数据,是关联当前指定国家的与没有关联任何国家的数据

$country_id = 73579;
        $instance = NewsModel::with(['country'])->where('status',1);
        $instance->where(function($query) use ($country_id){
            $query->whereHas('countryrel', function ($query) use ($country_id) {
                $query->where('country_id', $country_id);
            });
            $query->orWhereDoesntHave('countryrel',function(){
            });
        });
        $list = $instance->orderBy('id','desc')->limit(10)->get(['id','status','title']);

        print_r($list->toArray());exit;

联表查询且指定别名

 $field = ['a.id', 'a.type', 'a.app_version_id', 'a.status', 'b.version'];
        $instance = AppVersionChannelModel::from("app_version_channel as a")->join("app_version as b", 'b.id', '=', 'a.app_version_id');
        $instance->where('a.type', $channel);
        $instance->where('b.version', $version);
        $result = $instance->orderBy('a.id', 'desc')->first($field);
原文地址:https://www.cnblogs.com/zqsb/p/11975458.html