-
with用法
$accouts = Accounts::with('orders')->get();
sql相当于:
array:2 [▼
0 => array:3 [▼
"query" => "select * from `accounts`"
"bindings" => []
"time" => 17.0
]
1 => array:3 [▼
"query" => "select * from `orders` where `orders`.`accout_id` in (?, ?, ?, ?)"
"bindings" => array:4 [▶]
"time" => 1.0
]
]
$account查出来是一个集合转为数组的话则是三维数组,数据结构不在一个层级之上
-----------------------------------------------------------------------------------------
$accouts = Accounts::find(1)->orders()->get();
sql相当于:
array:2 [▼
0 => array:3 [▼
"query" => "select * from `accounts` where `accounts`.`id` = ? limit 1"
"bindings" => array:1 [▶]
"time" => 7.0
]
1 => array:3 [▼
"query" => "select * from `orders` where `orders`.`accout_id` = ? and `orders`.`accout_id` is not null"
"bindings" => array:1 [▶]
"time" => 1.0
]
]
$account查出来是一个集合转为数组的话则是二维数组,查询的结构是对应的关联模型数据
-----------------------------------------------------------------------------------------
$accouts = Accounts::with(['orders' => function($query){
$query->where('accout_id',1);
}])->get()->toArray();
sql相当于:
array:2 [▼
0 => array:3 [▼
"query" => "select * from `accounts`"
"bindings" => []
"time" => 8.0
]
1 => array:3 [▼
"query" => "select * from `orders` where `orders`.`accout_id` in (?, ?, ?, ?) and `accout_id` = ?"
"bindings" => array:5 [▶]
"time" => 1.0
]
]
可以使用闭包对关联的模型对象进行二次处理
$account查出来是一个集合转为数组的话则是三维数组,查询的关联数据如果没有则是空
with可以避免N + 1 的查询性能问题
-
associate用法
$account = Accounts::findOrFail(1);
$orders = new Orders();
$orders->accounts()->associate($account);
$orders->num =2;
$orders->save();
对应模型
class Orders extends Model
{
public $timestamps = false;
public $table = 'orders';
protected $fillable = ['num','test'];
public function accounts()
{
return $this->belongsTo(Accounts::class,'accout_id','id');
}
}
---------------------------------------------------------------------------
associate只有belongsTo的关系才能使用,模型保存时,会自动填充父模型的外键