這是我第一次嘗試使用雄辯relationship.I有的usermodel和phoneModel 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);
}
}
你會讓你的生活變得更容易,如果你遵循一些基本的約定,即類名應該以大寫字母開頭( '電話'而不是'電話')。 'Model'後綴是不必要的('Phone'而不是'phoneModel');並且表名應該多元化('電話'不只是'電話')。 –