Laravel日常使用总结

时间:2022-03-15 00:25:37

字段当做键值key

集合的keyBy()方法详情:戳这里

创建模型类和数据库迁移文件

php artisan make:model Post -m

创建控制器和基础的方法

php artisan make:controller PermissionController --resource

 子查询1.

SELECT COUNT(*) FROM
(SELECT * FROM abc GROUP BY col1) AS a;

laravel代码

$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
->count();

子查询2.

SELECT
`p`.`id`
FROM `products` p
WHERE `p`.`id` IN (
SELECT
`product_id`
FROM `product_category`
WHERE `category_id` IN ('1', '2')
)
AND `p`.`active`=1

laravel代码

Products::whereIn('id', function($query){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', ['1', '2'])
->where('active', 1);
})->get();