Laravel 关系、模型和迁移

Laravel Relations, Models and Migrations

我在 laravel 中的关系有问题: 我有两个表,语言和 Customers.The 客户只能有 1 种语言。这些是我的迁移和模型:

迁移:

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

所以,如果我进行查询,我会遇到下一个错误:

error

为什么?如果迁移具有 Laravel 所说的标准

如果我像这样更改客户模型:

public function language(){
    return $this->hasMany(Language::class,'id','language_id');
}

效果不错,但语言不行

希望大家能帮帮我。

将此添加到您的 Customer 模型中:

public function language(){
  return $this->belongsTo('App\Language');
}

这对你的 Language 模型:

public function customers(){
  return $this->hasMany('App\Customer');
}