dtpxi88884 2018-09-07 12:35
浏览 48
已采纳

Laravel雄辩的模特关系

My app builds on

Laravel: 5.6.35
PHP 7.2.4
Entrust: 1.9

My Role model

class Role extends EntrustRole
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

And my User model is

class User extends Authenticatable
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    } 
}

And now you can notice in Tinker

D:\work\www\myapp>php artisan tinker
Psy Shell v0.9.7 (PHP 7.2.4 — cli) by Justin Hileman
>>> App\models\Role::find(1)->users()->get()
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.role_id' in 'where clause' (SQL: select * from `users` where `users`.`role_id` = 1 and `users`.`role_id` is not null)'
>>> App\User::find(1)->role()->get();
=> Illuminate\Database\Eloquent\Collection {#2937
     all: [],
   }
>>> App\User::find(1)->roles()->get();
=> Illuminate\Database\Eloquent\Collection {#2941
     all: [
       App\models\Role {#2930
         id: 1,
         name: "super-admin",
         display_name: "Super Admin",
         description: "This will be one permission, that can not be assigned or modified.",
         created_at: "2018-09-07 12:11:35",
         updated_at: "2018-09-07 12:11:35",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2927
           user_id: 1,
           role_id: 1,
         },
       },
     ],
   }

I am getting result for App\User::find(1)->roles(), but my User model has function role(), and empty collection for App\User::find(1)->role() and error for App\models\Role::find(1)->users()

so please give some idea, how to solve this issue?

  • 写回答

3条回答 默认 最新

  • duanqiao8925 2018-09-07 12:53
    关注

    I think I found the answer to my question here.if you have properly defined relations through hasMany and belongsTo in your models, but haven't provided foreign key in the table of the model who belongsTo other table, your relations won't work. In documentation too, it suggests to use foreign_key to use One-to-Many relationship.

    Entrust database design is based on many-to-many relationship. So that user can have multiple roles.Purly as described in Laravel documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line