You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:45:49