如何让User模型查询时自动调用with('country')并合并其他关联?
Laravel模型自动预加载关联解决方案
要实现User模型每次查询都自动加载country关联,不管是否手动指定其他关联,只需要利用Laravel内置的全局预加载功能即可,具体操作如下:
具体实现
在你的User模型文件中,添加$with属性并指定需要自动加载的关联:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { // 全局预加载country关联,所有查询都会自动携带该关联数据 protected $with = ['country']; // 定义与Country模型的关联关系 public function country() { return $this->belongsTo(Country::class); } // 示例:其他关联方法(比如role) public function role() { return $this->belongsTo(Role::class); } }
效果验证
- 执行
User::get();时,会自动加载所有用户的country关联数据,无需手动调用with('country') - 执行
User::with('role')->get();时,会同时加载role和country两个关联的数据,不会仅返回role关联
补充:临时取消全局预加载
如果某一次查询不需要加载country关联,可以使用without('country')临时关闭全局预加载:
// 本次查询不自动加载country关联 User::without('country')->get();
内容的提问来源于stack exchange,提问作者Ameer Hamza
相关产品推荐
相关产品推荐

