【问题标题】:how to assign first loop to second loop and so on in laravel?如何在laravel中将第一个循环分配给第二个循环等等?
【发布时间】:2021-08-30 01:57:01
【问题描述】:

我有一个表 Permission,它具有权限名称、类型、实体,我喜欢在创建角色时将其显示在表中

我通过三个变量从一个类权限的控制器创建一个页面

    $types=Permission::select('type')->groupBy('type')->get();
    $entities=Permission::select('entity')->groupBy('entity')->get();
    $permission=Permission::select('id','name')->get();

现在如果Type=Admin如何显示以下,只显示以下Entity和权限。 这是权限模型

    class Permission extends Model
{
    use HasFactory,Uuids;
 protected $fillable = ['id','name','type','entity'];
      public function roles()
    {
        return $this->belongsToMany(Role::class, 'permission_role');
    }
     
}

谢谢

【问题讨论】:

  • "Type=Admin" - 你不想像这样过滤吗:Permission::select('type')->where('type', 'Admin')->groupBy('type')->get()?
  • 其他类型怎么样,我的情况有7种以上
  • 好吧,我敢打赌,我把那一段弄错了。你可能需要relationships
  • 你之前没有提到角色。它们如何适应?

标签: php laravel eloquent laravel-blade


【解决方案1】:

你需要relationships。

你的模型:

class Type extends Model
{
    public function entities()
    {
        return $this->hasMany(Entity::class);
    }
}
class Entity extends Model
{
    public function permissions()
    {
        return $this->hasMany(Permission::class);
    }
}

你的刀片视图:

<table>
    @foreach($types as $type)
        <tr>
            <th colspan="6">{{ $type->type }}</th>
        </tr>
        @foreach($type->entities as $entity)
            <tr>
                <th>{{ $entity->entity }}</th>
                @foreach($entity->permissions as $permission)
                    <td>{{ $permission->name }}</td>
                @endforeach
            </tr>
        @endforeach
    @endforeach
</table>

【讨论】:

  • 我尝试使用一个类权限(名称,实体,类型)是可能的,只有在权限类中
  • $types=Permission::select('type')->groupBy('type')->get(); $entities=Permission::select('entity')->groupBy('entity')->get(); $permission=Permission::select('id','name')->get();
  • 我敢打赌不是,但这取决于您的设置。为此,您必须分享您的 Permission 模型的代码。
  • 类权限扩展模型 { 使用 HasFactory,Uuids; protected $fillable = ['id','name','type','entity'];公共函数角色(){返回$this->belongsToMany(角色::类,'permission_role'); } }
  • 能否将其放在您的问题中以提高可读性?
猜你喜欢
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2013-08-04
相关资源
最近更新 更多