Laravel Eloquent 自定义返回字段

发布时间: 2018-12-19 14:30:35 作者: 大象笔记

返回指定字段

Book::select("price", "name")->all();

返回关系字段关联的属性

Book::select("price", "name", "author_id")->with('author')->all();

注意,如果要返回关系字段的信息,一定要将对应的 id 字段加入到 select 中。否则关系字段会显示为 null.

返回关系字段关联的指定属性

Book::select("price", "name", "author_id")->with('author:id,name')->all();

eager load

With 这种写法,在 laravel 中称之为 eager load。

Eager:热切渴求的。

对应的,laravel eloquent 查询的默认行为为 lazy load, 即默认不返回关系字段的详细信息,即不进行 left join。

返回 SQL 公式的复杂字段

一定要使用 selectRaw !!!

用了 DB::raw 只能徒增烦恼:

各种错误

Invalid parameter number

Invalid parameter number: mixed named and positional parameters

用了 selectRaw 世界就清净了

$shops = User::selectRaw("
    id, store_name, tel, county_name,
    store_address, longitude, latitude,
    SQRT(
        POW(69.1 * (latitude - ?), 2) +
        POW(69.1 * (? - longitude) * COS(latitude / 57.3), 2)
    ) AS distance", [$latitude, $longitude]
)->where('city_id', $city_id)
    ->orderBy('distance', 'desc')
    ->get();

$filtered = $shops->filter(function ($shop, $key) {
    return $shop->hasRole('市级代理') || $shop->hasRole('区级代理');
});

我是一名山东烟台的开发者,联系作者