2016-02-18 20 views
0

這是我第一次嘗試使用雄辯relationship.I有的usermodelphoneModel class.They分別代表用戶電話表。在這裏,我試圖訪問一個用戶的電話號碼時,他/她登錄。類「手機」未找到,同時實施雄辯關係

用戶表具有字段(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'); 
    }); 
} 

我施加hasOne和上兩種模型belongs to關係:

userModel.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'); 
    } 

} 

phoneModel.php:

namespace App; 

use Illuminate\Database\Eloquent\Model; 

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

現在,當我試圖讓從登錄的用戶的電話號碼,我得到所謂的類「錯誤手機'找不到

這是UserController中的表演方法裏面的代碼:

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); 
    } 
} 
+0

你會讓你的生活變得更容易,如果你遵循一些基本的約定,即類名應該以大寫字母開頭( '電話'而不是'電話')。 'Model'後綴是不必要的('Phone'而不是'phoneModel');並且表名應該多元化('電話'不只是'電話')。 –

回答

3

你命名你的手機類phoneModel但你添加的關係爲$this->hasOne('App\Models\phone');。您還在App命名空間中創建了這些類,但將其引用爲App\Models\class

標準做法是在模型後面使用大寫字母命名模型類。所以你的班級將被稱爲UserPhone,而不是userModelphoneModel。數據庫表格將是usersphones。如果你使用這些標準,Laravel將在幕後自動處理很多事情。

User類

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'); 
    } 
+0

使用userModel或phoneModel的模型名稱的雄辯關係是否存在任何問題?我如何在我的代碼中使用這些名稱..您更改了類名 –

+0

否,您可以使用'return $ this-> belongsTo('App \ userModel');'和'$ this-> hasOne('App \ phoneModel');'。這些將起作用。但改變表格和類名會讓你更容易。對於所有PHP代碼來說,最好的做法是使用大寫字母作爲類。 – Jeff