php - 在 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))
解决方案
您必须指定自定义外键:
public function investors() {
return $this->hasMany('App\GoldPurchaseInvestor', 'purchase_id');
}
但这实际上是一个BelongsToMany
关系的例子:
public function investors() {
return $this->belongsToMany('App\Investor', 'gold_purchase_investor', 'purchase_id');
}
推荐阅读
- javascript - Proactive MutationObserver - 在添加到 DOM 之前拦截节点
- javascript - 错误返回数据foreach查找mongodb数组
- java - 找不到命令:jdeprscan
- python - 如何从两个列表中选择对/?
- azure - Azure 服务总线 Restful Api 获取
- github - 如何将 .gitmodules 直接提取到其 github 存储库中?
- python - Python 外观失败,我不知道为什么:IndexError: list index out of range
- html - 停止显示:下拉扩展元素?
- python - 带有 ID 数组的单个 zcat 多个提取
- ios - 如何在导航栏中的导航图标附近隐藏标题ios swift