我正在研究我的laravel项目中用户的访问权限和权限我想显示模块的功能,所以我可以将它们添加到某个角色这里是我的数据库:
public function up()
{
Schema::create('role_modules', function (Blueprint $table)
{
$table->increments('id');
$table->integer('rang');
$table->string('title');
$table->string('route');
$table->text('description');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('role_modules');
}
public function up()
{
Schema::create('role_functions', function (Blueprint $table)
{
$table->increments('id');
$table->integer('module_id')->unsigned();
$table->string('title');
$table->string('function');
$table->softDeletes();
$table->timestamps();
$table->foreign('module_id')->references('id')->on('role_modules')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('role_functions');
}
这是我的模型代码:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Rolemodules extends Model
{
protected $table = 'role_modules';
public function func()
{
return $this->hasMany('App\Rolefunctions','module_id');
}
}
当我想在我的视图中显示每个模块的功能时:
@foreach($rolemodules as $rolemodule)
{{$rolemodule->func['title']}}
@endforeach
我收到此错误:未定义索引:标题
答案 0 :(得分:2)
由于Rolemodules
有许多Rolefunctions
将代码更改为:
@foreach ($rolemodules as $rolemodule)
@foreach ($rolemodule->func as $func)
{{ $func->title }}
@endforeach
@endforeach
答案 1 :(得分:1)
当您将集合返回到视图时,您需要load
这样的关系:
$roleModel->load('func');
然后你可以在你的视图中使用它:
@foreach($rolemodules as $rolemodule)
@foreach($rolemodule->func as $obj)
{{ $obj->title }}
@endforeach
@endforeach
答案 2 :(得分:1)
使用如下:
@foreach($rolemodules as $rolemodule)
{{$rolemodule->func->title}}
@endforeach