使用 laravel 从多对多检索数据

Posted

技术标签:

【中文标题】使用 laravel 从多对多检索数据【英文标题】:retrieving data from many to many using laravel 【发布时间】:2012-12-26 22:58:57 【问题描述】:

我有 2 个表和一个数据透视表。表的结构如下所述。

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 我得到的只是一个消息数组,有人可以指导我如何获取记录吗?

【问题讨论】:

【参考方案1】:

首先,用户应该扩展 Eloquent。此外,您应该创建一个角色模型。

//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

【讨论】:

我在我的 Basemodel 中扩展了 eloquent 类。 :) 但非常感谢您的帮助 :)【参考方案2】:

您应该在您的视图中迭代 $menu 数组:

@foreach ($menu as $menu_item)
   $menu_item->id  # output ID of a record
@endforeach

【讨论】:

以上是关于使用 laravel 从多对多检索数据的主要内容,如果未能解决你的问题,请参考以下文章

从多对多关系的桥接表中检索数据的查询[关闭]

如何在 Laravel 中从多对多关系的一对多关系中获取项目?

如何从多对多关系中只加载 1 个结果 Laravel

从多对多连接表中检索行的 HQL 查询

使用实体框架从多对多关系中选择数据

使用非关联数据 (LINQ) 从多对多关系中获取值