Laravel中如何在Eloquent查询中调用模型非关联方法?
解决方法
报错的原因很直接:with()方法是用来预加载Eloquent关联关系的,它要求传入的方法必须返回一个关联实例(比如hasOne、belongsTo这类关联定义)。而你的test()是普通模型方法,返回的是字符串,框架尝试调用关联的addEagerConstraints()方法时自然会报错。
你可以用以下几种方式实现需求:
1. 直接调用实例方法
既然已经拿到$player实例,直接调用方法就行,不需要在查询阶段处理:
$player = Player::with('animals')->findOrFail($id); $testValue = $player->test();
2. 用访问器+追加属性(推荐)
如果希望test的值自动作为模型属性存在,可以把test()改成访问器,并配置模型的$appends属性:
修改Player模型:
class Player extends Model { use HasFactory; protected $fillable = [ 'user_id', 'player_name', 'player_level', 'player_day' ]; // 追加test属性到模型实例 protected $appends = ['test']; public function animals() { return $this->hasOne(Animal::class); } // 定义访问器 public function getTestAttribute() { return "z"; } }
之后查询时,$player->test就能直接拿到值,和with('animals')完全兼容:
$player = Player::with('animals')->findOrFail($id); // 直接访问$player->test即可获取"z"
3. 查询时手动添加字段(适合固定值/可SQL生成的情况)
如果test的返回值是固定字符串或者可以通过SQL表达式生成,也可以在查询时直接select这个字段:
use Illuminate\Support\Facades\DB; $player = Player::with('animals') ->select('*', DB::raw('"z" as test')) ->findOrFail($id);
这种方式下,$player->test也能拿到对应的值。
内容的提问来源于stack exchange,提问作者ferter3006
相关产品推荐
相关产品推荐

