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

Laravel Eloquent关联查询报错:str_contains()参数类型错误

问题排查与修复

1. 控制器with方法调用错误

你当前的with写法违反Laravel语法规范,将闭包直接作为第二个参数传递,导致Laravel误把闭包当作关联名称字符串处理,触发str_contains类型错误。

正确写法需将关联关系与约束闭包放入数组:

public function index()
{
    $user = User::with(['connections' => function($q){
        $q->where('status','accepted');
    }, 'connections.reciver'])->find(\Auth::user()->id);
    return response()->json($user);
}

或嵌套约束的简洁写法:

public function index()
{
    $user = User::with(['connections' => function($q){
        $q->where('status','accepted')->with('reciver');
    }])->find(\Auth::user()->id);
    return response()->json($user);
}

2. 模型中的拼写错误

(1)类名拼写错误

Connection模型多处出现User::calss,正确应为User::class(缺字母s):

// 错误写法
public function users(){
    return $this->belongsToMany(User::calss);
}

public function sender(){
    return $this->belongsTo(User::calss,'sender_id');
}

// 正确写法
public function users(){
    return $this->belongsToMany(User::class);
}

public function sender(){
    return $this->belongsTo(User::class,'sender_id');
}

(2)字段名拼写错误

reciver为拼写错误,正确应为receiver,建议统一修正:

  • 数据库表字段reciver_id改为receiver_id
  • Connection模型关联方法修改:
public function receiver(){
    return $this->belongsTo('App\Models\User','receiver_id');
}
  • User模型与控制器中的关联调用同步改为connections.receiver

3. 补充:双向连接查询优化

若需获取当前用户作为发送者和接收者的所有已接受连接,需在User模型补充关联:

// User模型
public function receivedConnections(){
    return $this->hasMany(Connection::class,'receiver_id');
}

控制器中同时查询两种场景并合并结果:

public function index()
{
    $user = User::with([
        'connections' => function($q){
            $q->where('status','accepted')->with('receiver');
        },
        'receivedConnections' => function($q){
            $q->where('status','accepted')->with('sender');
        }
    ])->find(\Auth::user()->id);
    
    $connectedUsers = collect()
        ->merge($user->connections->pluck('receiver'))
        ->merge($user->receivedConnections->pluck('sender'))
        ->unique('id');
    
    return response()->json(['user' => $user, 'connected_users' => $connectedUsers]);
}

内容的提问来源于stack exchange,提问作者moslem parve

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:35:28