简体   繁体   English

Laravel 5.2嵌套口才关系

[英]Laravel 5.2 Nested Eloquent relationships

I have a User which is of type Player and has several Equipments 我有一个播放器类型的用户,并且有多个设备

I want to request a piece of Equipment and see if the User is it's owner before returning it to the user. 我想请求一件设备,然后将其退还给用户,看看用户是否是它的所有者。 If they do not own it they will get an unauthorized response 如果他们不拥有它,他们将收到未经授权的回复

Here are the relationships I have for the models: 这是我与模型之间的关系:

App\\User.php App \\ User.php
class Equipment extends Model
{
    protected $table = 'equipement';

    public function player()
    {
        return $this->belongsTo(Player::class);
    }
}
App\\Player.php App \\ Player.php
 class Player extends Model { protected $table = 'player'; public function equipment() { return $this->hasMany(Equipment::class); } public function user() { return $this->belongsTo(User::class); } } 
App\\Equipment.php App \\ Equipment.php
 class Equipment extends Model { protected $table = 'equipement'; public function player() { return $this->belongsTo(Player::class); } } 
EquipmentController.php EquipmentController.php

With my attempt which is working... just very ugly. 根据我的尝试,这很丑。

 class EquipmentController extends Controller { public function show($id) { $equipment = Equipment::find($id); if ( ! $equipment ) { return 'Equipment does not exist'); } // my attempt $test = Equipment::with('player.user')->findOrFail($id); if ($test->toArray()['player']['user']['id'] != Auth::user()->id){ return 'Unauthorized'; } // return $equipment; } } 

Is there a neater way to do this? 有没有更整洁的方式做到这一点?

I want something readable in the controller like: 我想要在控制器中可读的内容,例如:

 if(!$equipment->ownedBy(Auth::user())){ return 'Unauthorized'; } 

Or something similarly as readable. 或类似的可读性。

And once the relationship is found, I'm not sure where the logic should be placed. 一旦找到关系,我不确定逻辑应该放在哪里。 Should it be in the Equipment model? 应该在设备模型中吗? Any help would be much appreciated! 任何帮助将非常感激!

In your Equipment model: 在您的Equipment模型中:

public function authorized()
{
   return ($this->player->user->id == auth()->user()->id())
} 

Then from your controller, try: 然后从您的控制器尝试:

$equipment->authorized() //returns true or false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM