首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对未定义方法Illuminate\Database\Eloquent\Builder::privilege()的Laravel调用

对未定义方法Illuminate\Database\Eloquent\Builder::privilege()的Laravel调用
EN

Stack Overflow用户
提问于 2019-05-05 14:18:28
回答 2查看 2.2K关注 0票数 0

我想在用户集合中显示privileges('name')而不是idPrivilege。我试图添加一种关系,并使用它在一个雄辩的电话,但我得到了一个错误。

用户模型

代码语言:javascript
复制
namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';

    protected $primaryKey = 'idUser';

    protected $fillable = [
        'name', 'email',
    ];

    protected $hidden = [
        'password', 'updated_at',
    ];

    public function privilege()
    {
        return $this->hasOne(Privilege::class, 'idPrivilege', 'idPrivilege');
    }
}

特权模型

代码语言:javascript
复制
namespace App;

use Illuminate\Database\Eloquent\Model;

class Privilege extends Model
{
    protected $table = 'privileges';

    protected $primaryKey = 'idPrivilege';

    protected $fillable = [
        'name',
    ];

    protected $hidden = [
        'updated_at', 
    ];

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

UserController

代码语言:javascript
复制
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
    public function relationTest()
    {
        return User::where('idUser', 1)->privilege()->get();
    }
}

当我使用with('privilege')到我的用户集合是添加特权集合时,我会得到以下错误。

调用未定义方法Illuminate\Database\Eloquent\Builder::privilege().

EN

回答 2

Stack Overflow用户

发布于 2019-05-05 14:21:54

where返回一个不存在privilege方法的Builder实例,因此您可以这样使用它:

代码语言:javascript
复制
return User::find(1)->privilege()->get();;

-编辑

代码语言:javascript
复制
User::find(1)->with(['privilege' => function($query) { 
   $query->select('name');
}])->get();
票数 0
EN

Stack Overflow用户

发布于 2019-05-05 15:00:09

我可以通过使用资源来实现这一点:

代码语言:javascript
复制
$user = User::where('idUser', 1)->with('privilege')->first();
return UserResource::make($user);

在UserResource内部:

代码语言:javascript
复制
public function toArray($request)
{
    return [
        'idUser' => $this->idUser,
        'name' => $this->name,
        'email' => $this->email,
        'privilege' => $this->privilege['name'],
        'createdAt' => $this->created_at,
    ];
}

但我希望有更简单的方法。

产出:

代码语言:javascript
复制
{
"data": {
"idUser": 1,
"name": "Martin",
"email": "martin@martin.martin",
"privilege": "user",
"createdAt": "2019-05-05T01:11:43.000000Z"
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55992906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档