【问题标题】:retrieving data from many to many using laravel使用 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}} 我得到的只是一个消息数组,有人可以指导我如何获取记录吗?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 2017-02-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2013-03-29
      相关资源
      最近更新 更多