首页 > 解决方案 > 在 laravel eloquent 中处理映射表

问题描述

在我的申请中,将有多个投资者标记为单次购买条目。因此,在加载购买条目时,我应该让所有投资者相关联。

在我的控制器中,

return response()->json(GoldPurchase::with('investors')->get());

映射表架构,

Schema::create('gold_purchase_investor', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('investor_id')->unsigned();
   $table->integer('purchase_id')->unsigned();
   $table->timestamps();

   $table->foreign('investor_id')
        ->references('id')
        ->on('investors')
        ->onDelete('cascade');

   $table->foreign('purchase_id')
        ->references('id')
        ->on('gold_purchases')
        ->onDelete('cascade');
});

购买型号,

class GoldPurchase extends Model
{
    public function investors() {
        return $this->hasMany('App\GoldPurchaseInvestor');
    }
}

投资人模式,

class Investor extends Model
{
    protected $fillable = ['name', 'address', 'mobile', 'email'];

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

购买投资者模型,

class GoldPurchaseInvestor extends Model
{
    protected $table = 'gold_purchase_investor';

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

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

有了这个,我得到了错误,

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'gold_purchase_investor.gold_purchase_id' in 'where clause' (SQL: select * from `gold_purchase_investor` where `gold_purchase_investor`.`gold_purchase_id` in (1))

标签: phpmysqllaravellaravel-5eloquent

解决方案


您必须指定自定义外键:

public function investors() {
    return $this->hasMany('App\GoldPurchaseInvestor', 'purchase_id');
}

但这实际上是一个BelongsToMany关系的例子:

public function investors() {
    return $this->belongsToMany('App\Investor', 'gold_purchase_investor', 'purchase_id');
}

推荐阅读