我在表中有自定义字段,并希望MorpTohmany与其他表。如何使用自定义字段。
在以下型号( salepurchase ) request_to 是供应商型号外键,其中 salepurchase_type < / strong>和 salepurchase_id 这些将包含其他模型关系,如仓库,商店等
SalePurchase 型号
+----+------------+-------------------+-----------------+-------------+
| id | request_to | salepurchase_type | salepurchase_id | total_items |
+----+------------+-------------------+-----------------+-------------+
| 1 | 1 | Warehouse | 1 | 10 |
| 2 | 1 | Warehouse | 1 | 10 |
| 3 | 1 | Warehouse | 1 | 11 |
| 4 | 1 | Shop | 7 | 15 |
| 5 | 1 | Shop | 5 | 19 |
+----+------------+-------------------+-----------------+-------------+
仓库型号
+----+-------------+
| id | name |
+----+-------------+
| 1 | warehosue 1 |
| 2 | warehosue 2 |
购物型号
+----+-------------+
| id | name |
+----+-------------+
| 5 | Shop 1 |
| 7 | Shop 2 |
供应商型号
+----+--------------------------+
| id | qualified_person |
+----+--------------------------+
| 1 | Marks |
| 2 | test |
+----+--------------------------+
答案 0 :(得分:0)
在您的模型中,只需添加关系:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SalePurchase extends Model
{
/**
* Get all of the owning salepurchase models.
*/
public function salepurchase()
{
return $this->morphTo();
}
public function supplier()
{
return $this->belongsTo('App\Supplier','request_to','id');
}
}
然后在其他模特中:
class Shop extends Model
{
/**
* Get all of the Shop's purchases.
*/
public function salepurchases()
{
return $this->morphMany('App\SalePurchase', 'salepurchase');
}
}
在您的供应商模型中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model
{
public function salepurchases()
{
return $this->hasMany('App\SalePurchases');
}
}
我认为这里不需要MorphedByMany。由于SalePurchases表保存了Morphed字段。