我想在用户集合中显示privileges('name')
而不是idPrivilege
。我试图添加一个关系并将其用于Eloquent通话中,但出现错误。
用户模型
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');
}
}
特权模式
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
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()。
答案 0 :(得分:0)
where
返回一个Builder
方法实例,在该实例上不存在privilege
方法,因此您可以这样简单地使用它:
return User::find(1)->privilege()->get();;
-编辑
User::find(1)->with(['privilege' => function($query) {
$query->select('name');
}])->get();
答案 1 :(得分:0)
我可以使用资源来实现它:
$user = User::where('idUser', 1)->with('privilege')->first();
return UserResource::make($user);
内部UserResource:
public function toArray($request)
{
return [
'idUser' => $this->idUser,
'name' => $this->name,
'email' => $this->email,
'privilege' => $this->privilege['name'],
'createdAt' => $this->created_at,
];
}
但希望有一种更简单的方法来获得它。
输出:
{
"data": {
"idUser": 1,
"name": "Martin",
"email": "martin@martin.martin",
"privilege": "user",
"createdAt": "2019-05-05T01:11:43.000000Z"
}
}