阅读(2279) (0)

Laravel 8 默认预加载

2021-07-08 09:44:49 更新

有时可能希望在查询模型时始终加载某些关联。 为此,你可以在模型上定义 $with 属性:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * 默认加载的关联
     *
     * @var array
     */
    protected $with = ['author'];

    /**
     * 获取书籍作者
     */
    public function author()
    {
        return $this->belongsTo('App\Models\Author');
    }
} 

如果你想从单个查询的 $with 属性中删除一个预加载,你可以使用 without 方法:

$books = App\Models\Book::without('author')->get();