我在laravel中的关系有问题: 我有两个表,语言和客户。客户只能有一种语言。这些是我的迁移和模型:
迁移:
Schema::create('tbl_customers', function (Blueprint $table){
$table->increments('id');
$table->string('first_name',255);
$table->string('last_name',255);
$table->date('date_of_birth');
$table->string('email',255);
$table->string('phone_number',255);
$table->string('phone_number2',255);
$table->string('password', 255);
$table->unsignedInteger('dealer_id');
$table->string('picture_profile',255);
$table->string('occupation',255);;
//Foreign key
$table->unsignedInteger('language_id');
$table->string('about_me',255);
});
Schema::create('tbl_languages', function (Blueprint $table){
$table->increments('id');
$table->string('language',255);
});
这是外键:
Schema::table('tbl_customers', function (Blueprint $table){
$table->foreign('language_id')->references('id')
->on('tbl_languages')->onDelete('cascade');
});
这些是我的模特。 客户:
class Customer extends Model{
protected $table='tbl_customers';
protected $primaryKey="id";
protected $fillable=['address_id','first_name','last_name','gender_id','date_of_birth','email','phone_number','phone_number2',
'dealer_id','picture_profile','occupation','time_zone_id','language_id','about_me'];
protected $hidden=['password'];
public $timestamps = false;
public function language(){
return $this->hasMany(Language::class);
}}
语言
class Language extends Model{
protected $table='tbl_languages';
protected $primaryKey="id";
protected $fillable=['language'];
public $timestamps=false;
public function customers(){
return $this->belongsToMany(Customer::class);
}}
所以,如果我进行查询,我会遇到下一个错误:
为什么呢?如果迁移具有Laravel所说的标准
如果我更改Customer模型:
public function language(){
return $this->hasMany(Language::class,'id','language_id');
}
效果很好,但语言没有。
我希望你们能帮助我。
答案 0 :(得分:1)
将此添加到您的Customer
模型中:
public function language(){
return $this->belongsTo('App\Language');
}
这是您的Language
型号:
public function customers(){
return $this->hasMany('App\Customer');
}