PHP 致命错误:调用未定义的函数 Laravel Tinker

我试图在两个表(角色和能力)之间建立关系,但是当我运行该函数时,allowTo()它说 is undefined。我尝试清除缓存和配置,但没有执行任何操作。如果有人能提供帮助那就太好了,谢谢!


型号:


<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class Role extends Model

{

    

protected $guarded = [];


    public function abilities(){

        return $this->belongsToMany(Ability::class)->withTimestamps();

    }


   public function allowTo($ability){


        $this->abilities()->save($ability);

   }

shell 上的 Tinker 环境:


>>> $user = App\User::find(7);


=> App\User {#3044

     id: 7,

     name: "Rebeca Tejedor",

     email: "rebtej@gmal.com",

     email_verified_at: null,

     created_at: "2020-08-13 10:29:46",

     updated_at: "2020-08-13 10:29:46",

   }

>>> $role = Role::firstOrCreate(['name'=> 'lender']);


[!] Aliasing 'Role' to 'App\Role' for this Tinker session.

=> App\Role {#3041

     id: 1,

     name: "lender",

     created_at: "2020-08-13 10:41:15",

     updated_at: "2020-08-13 10:41:15",

   }

>>> $ability = Ability::firstOrCreate(['name'=> 'edit_items']);


[!] Aliasing 'Ability' to 'App\Ability' for this Tinker session.

=> App\Ability {#3040

     id: 1,

     name: "edit_items",

     created_at: "2020-08-13 10:43:34",

     updated_at: "2020-08-13 10:43:34",

   }


>>> $role = allowTo($ability)

错误:


PHP Fatal error:  Call to undefined function allowTo() in Psy Shell code on line 1

该模型

修补匠环境


MM们
浏览 65回答 1
1回答

慕妹3146593

您以这种方式使用您的关系:$role&nbsp;=&nbsp;allowTo($ability);虽然你应该像这样使用它:$role->allowTo($ability);并在你的方法中:public&nbsp;function&nbsp;allowTo($ability)&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;$this->abilities()->attach($ability->id); }
打开App,查看更多内容
随时随地看视频慕课网APP