首页 > 解决方案 > Laravel:在字符串上调用带有()的成员函数

问题描述

因为我还是初学者,所以我在 Laravel 上苦苦挣扎。在我的web.php我有以下路线

Route::get('/customize/{id}', function ($id) {
    if (User::where('id','=','4')->has('profile'->with('id',$id))->exists() && Profile::where('user_id', $id)->exists()) {
        return true;
    }      
    
    return false;
});

我知道有些不对劲。

基本上我想要做的是,仅当具有4的用户的个人资料与url 中的个人资料相同时才返回 true。idid

在我的用户模式中,我有以下关系:

public function profile()
{        
    return $this->hasMany(Profile::class);
}

配置文件表示例:

https://i.stack.imgur.com/6Wr80.png

标签: laravel

解决方案


你有一个错字。

if (User::where('id','=','4')->has('profile'->with('id',$id))->exists() && Profile::where('user_id', $id)->exists()) {

应该

if (User::where('id','=','4')->has('profile')->with('id',$id)->exists() && Profile::where('user_id', $id)->exists()) {

通过这样做'profile'->with(...),您正在调用with(...)字符串 () 上的成员函数 ( 'profile')。


仅当 ID 为 4 的用户的个人资料 ID = $id 时才返回true,您想使用whereHas.

if (
    User::where('id', 4)->whereHas('profile', function ($query) use ($id) {
        return $query->where('id', $id);
    })
    ->exists()
) { ... }

使用 PHP ^7.4,这可以用简写闭包更紧凑地编写。

if ( User::where('id', 4)->whereHas('profile', fn($query) => $query->where('id', $id))->exists() ) { ... }

顺便说一句,在使用 时where()/orWhere(),如果不使用运算符,则默认为'='sowhere('id', '=', 4)可以写为 just where('id', 4)


推荐阅读