Php 使用laravel从多对多检索数据
我有两张桌子和一张透视表。表的结构如下所述Php 使用laravel从多对多检索数据,php,laravel,eloquent,Php,Laravel,Eloquent,我有两张桌子和一张透视表。表的结构如下所述 users table: id username password 1 admin xyzasd roles table: id name 1 role1 2 role2 role_user table: id user_id role_id 1 1 1 2 1 2 我的用户模型: class User extends Basemodel{ public static $tabl
users table:
id username password
1 admin xyzasd
roles table:
id name
1 role1
2 role2
role_user table:
id user_id role_id
1 1 1
2 1 2
我的用户模型:
class User extends Basemodel{
public static $table = 'users';
public static $timestamps = true;
public function roles()
{
return $this->has_many_and_belongs_to('Role');
}
public static function menu(){
$roles = User::find(1)->roles()->get();
return $roles;
}
}
我的控制器:
public function get_index()
{
return View::make('home.index')
->with('title','testing many to many')
->with('menu',User::menu());
}
在我的刀片视图文件中,我有一个语句{{$menu}},我得到的只是一个消息数组,有人能指导我如何获取记录吗 您应该在视图中迭代
$menu
数组:
@foreach ($menu as $menu_item)
{{ $menu_item->id }} # output ID of a record
@endforeach
您应该在视图中迭代
$菜单
数组:
@foreach ($menu as $menu_item)
{{ $menu_item->id }} # output ID of a record
@endforeach
首先,用户应该有口才。此外,您还应该创建一个角色模型 //application/models/User.php
class User extends Eloquent
{
public static $table = 'users';
public static $timestamps = true;
public function roles()
{
return $this->has_many_and_belongs_to('Role');
}
}
//application/models/Role.php
class Role extends Eloquent
{
public static $table = 'roles';
public static $timestamps = true;
public function users()
{
return $this->has_many_and_belongs_to('User');
}
}
那么对于你的控制器,你基本上可以通过用户
public function get_index()
{
$user = User::find(1);
return View::make('home.index')
->with('title','testing many to many')
->with('user', $user);
}
在你看来,你可以做一些很酷的事情,比如:
<h1>What's up {{ $user->username }}?</h1>
<h2>You have the following roles:</h2>
@foreach($user->roles as $role)
<p>{{ $role->name }}</p>
@endforeach
怎么了{{{$user->username}?
您具有以下角色:
@foreach($user->roles as$role)
{{$role->name}
@endforeach
首先,用户应该扩展雄辩的语言。此外,您还应该创建一个角色模型
//application/models/User.php
class User extends Eloquent
{
public static $table = 'users';
public static $timestamps = true;
public function roles()
{
return $this->has_many_and_belongs_to('Role');
}
}
//application/models/Role.php
class Role extends Eloquent
{
public static $table = 'roles';
public static $timestamps = true;
public function users()
{
return $this->has_many_and_belongs_to('User');
}
}
那么对于你的控制器,你基本上可以通过用户
public function get_index()
{
$user = User::find(1);
return View::make('home.index')
->with('title','testing many to many')
->with('user', $user);
}
在你看来,你可以做一些很酷的事情,比如:
<h1>What's up {{ $user->username }}?</h1>
<h2>You have the following roles:</h2>
@foreach($user->roles as $role)
<p>{{ $role->name }}</p>
@endforeach
怎么了{{{$user->username}?
您具有以下角色:
@foreach($user->roles as$role)
{{$role->name}
@endforeach
我已经在我的基本模型中扩展了雄辩的类。:)但真的非常感谢您的帮助:)我已经在我的基本模型中扩展了雄辩的课程。:)但真的很感谢你的帮助:)