laravelelelounk中phpMap表的处理

z4bn682m  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(338)

在我的应用程序中,将有多个投资者标记为单个购买条目。所以在加载购买条目时,我应该让所有相关的投资者。
在我的控制器里,

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

Map表架构,

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

purchaseinvestor模型,

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))
jpfvwuh4

jpfvwuh41#

从雄辩的关系中:
记住,elokent将自动确定注解模型上正确的外键列。按照惯例,eloquent将使用所属模型的“snake case”名称并在其后面加上∗id。因此,对于本例,eloquent将假定注解模型上的外键是post∗id。

$this->hasMany('App\Comment', 'foreign_key', 'local_key');

因此,尝试在关系中写入外键和本地键
在你的情况下,我想应该是这样的:

class GoldPurchase extends Model`
{
    public function investors() {
        return $this->hasMany('App\GoldPurchaseInvestor', 'investor_id', 'id');
    }
}
0s7z1bwu

0s7z1bwu2#

使用 belongsToMany 多对多关系。
黄金采购.php

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

投资者.php

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

    public function purchases() {
        return $this->belongsToMany('App\GoldPurchase','gold_purchase_investor','investor_id','purchase_id');
    }
}

透视表根本不需要第三个模型。 GoldPurchaseInvestor 根本不需要。

8ehkhllq

8ehkhllq3#

必须指定自定义外键:

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

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

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

相关问题