在实现雄辩关系时找不到类“电话”


Class 'phone ' not found while implementing eloquent relationship

这是我第一次尝试使用雄辩关系。我有一个用户模型和一个电话模型类。它们分别代表用户电话表。在这里,我正在尝试访问用户登录时的电话号码。

用户表具有

字段(ID,名称,密码),电话表具有 (字段 ID,phone_no,user_id)

手机迁移如下:

public function up()
{
    //
    Schema::create('phone',function(Blueprint $table){
       $table->increments('id');
       $table->string('phone_no',20);
       $table->integer('user_id')->unsigned();
       $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

我在两个模型上应用了hasOnebelongs to关系:

用户型号.php

namespace App;
use Illuminate'Database'Eloquent'Model;
use Illuminate'Contracts'Auth'Authenticatable;
class userModel extends Model implements Authenticatable
{
    //
    use 'Illuminate'Auth'Authenticatable;
    protected $table = 'users';
    public function phone(){
             $this->hasOne('App'Models'phone');
    }
}

手机型号.php:

namespace App;
use Illuminate'Database'Eloquent'Model;
    class phoneModel extends Model
    {
        //
        protected $table='phone';
        public function user()
        {
            return $this->belongsTo('users');
        }
    }

现在,当我尝试从登录用户获取电话号码时,我收到一个名为"电话"类的错误,找不到

下面是 userController 的 show 方法中的代码:

public function show($user)
{
    //
    $indicator=is_numeric($user)?'id':'name';
    $info=userModel::where($indicator,'=',$user)->get()->first();
    if($info){
       $phone = userModel::find($info->id)->phone;
       $data=array('info'=>$info,'phone'=>$phone);
       return View::make('user.show')->with($data);
    }else{
      $info=userModel::where($indicator,'=', Auth::user()->name)->get()->first();
      return View::make('user.show')->with('user',$info);
    }
}

您将电话类命名为 phoneModel 但将关系添加为 $this->hasOne('App'Models'phone'); 。 您还在 App 命名空间中创建了这些类,但将它们作为 App'Models'class 引用。

标准做法是在模型之后命名模型类,并使用大写字母。 所以你的类将被称为UserPhone,而不是userModelphoneModel。 数据库表将是usersphones. 如果你使用这些标准,Laravel会在幕后自动处理很多事情。

用户类

namespace App;
class User extends Model implements Authenticatable
{
//
use 'Illuminate'Auth'Authenticatable;
//Laravel will assume the User model is in the table `users` so you don't need to specify
public function phone(){
         $this->hasOne('App'Phone');
}

电话类

namespace App;
class Phone extends Model
{
    //Laravel will assume the Phone model is in the table `phones` so you don't need to specify
    public function user()
    {
        return $this->belongsTo('App'User');
    }