机场表:
Schema::create('airports', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('city');
            $table->timestamps();
        });
航班表:
Schema::create('flights', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('number');
            $table->integer('origin')->unsigned();
            $table->foreign('origin')->references('id')->on('airports');
            $table->integer('destination')->unsigned();
            $table->foreign('destination')->references('id')->on('airports');
            $table->integer('price');
            $table->timestamps();
        });
飞行模型:
<?php
class Flight extends \Eloquent {
    protected $fillable = ['number', 'origin', 'destination'];
    public function origin(){
        return $this->belongsTo('Airport');
    }
    public function destination(){
        return $this->belongsTo('Airport');
    }
}
飞行控制器@索引:
public function index()
    {
        $flights = Flight::with('origin')->with('destination')->get();
        return Response::json($flights, 200);
    }
部分回复:
[
{
"id": "1",
"number": "112",
"origin": null,
"destination": null,
"price": "232",
"created_at": "2014-12-28 11:49:44",
"updated_at": …class A < ActiveRecord::Base
  has_many :Bs
  has_many :Cs
  ...
end
我想在A上进行查询时加载所有的B和C,比如A.where(name: :abc)使用单个查询,而不是多次调用数据库.
我不希望为.includes我运行的每个查询指定.如何在模型中指定预先加载?
我看了许多类似的问题并尝试这样做,但它不起作用:
default_scope :include => [:Bs, :Cs]
当我急切地加载这样的时候:
 return Port::filter($filters)
            ->with(['scores' => function ($query) {
                    $query->select(["*"]);
                }]
            )
            ->actives()
            ->paginate(14);
我得到了预期的结果.但是,当我选择特定的列名称时:
 return Port::filter($filters)
            ->with(['scores' => function ($query) {
                    $query->select(["id, name"]);
                }]
            )
            ->actives()
            ->paginate(14);
结果总是如此[].这可能有什么问题?
我有几个eager loaded关系Laravel 5.6.我想将数组键名更改为eager加载对象上的属性.
如何确保数组键0并1成为name属性(" COSTS"和" SAIL_BOAT_FRIENDLY")?
这甚至可能吗?
- 编辑
return Port::filter($filters)
            ->with('scores')
            ->actives()
            ->paginate(14);
得分关系
public function scores()
{
    return $this->hasMany(Score::class)
        ->select("id", "port_id", "name", DB::raw('AVG(score) as score'))
        ->groupBy('port_id', 'name');
}