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条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?