截至目前我有2个不同的ModelProductModel.php这是我的产品清单。ProductRelated.php这是每个特定产品分配的相关产品。场景是,如果我id = 1的ProductModel.id (primary key of Product Model)在我的ProductRelated.php我有这个prodID(这相当于id (primary key of Product Model) 这将用于识别相关产品被分配的特定产品 ID。prodRelatedID这是与该产品相关的产品。所以我ProductModel会有这些数据 id | prodTitle | prodDesc | More fields here... 1 | Product 1 | Description | More FIeld value here .. 2 | Product 2 | Description | More FIeld value here .. 3 | Product 3 | Description | More FIeld value here ..在我的ProductRelated遗嘱中有这些数据 id | prodID | prodRelatedID | More fields here... 1 | 1 | 2 | More FIeld value here .. 2 | 1 | 3 | More FIeld value here ..这意味着,id = 1来自ProductModel有 2 个不同的prodRelatedID这些是2 and 3我这样做的想法是使用hasMany()这是我的ProductModelnamespace App\Models;use Illuminate\Database\Eloquent\Model;use App\User;class ProductModel extends Model{public $timestamps = true;protected $table = 'product';/** * The attributes that are mass assignable. * * @var array */protected $fillable = [ 'id', 'prodTitle', 'prodDesc', 'prodCategory', 'attachment', 'prodSize', 'prodPrice', 'created_by', 'is_best_seller', 'prod_included', 'prod_instruction',];}我的ProductRelatednamespace App\Models;use Illuminate\Database\Eloquent\Model;use App\User;class ProductRelated extends Model{public $timestamps = true;protected $table = 'product_related';/** * The attributes that are mass assignable. * * @var array */protected $fillable = [ 'id', 'prodID', 'prodRelatedID', 'created_by'];}
1 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
如果您只想获取每个特定产品的所有相关产品,我认为您不需要ProductRelated
。
在你的ProductModel
public function relatedProducts() { return $this->belongsToMany(ProductModel::class, 'product_related', 'prodID', 'prodRelatedID'); }
然后你应该能够获取所有记录,如下所示:
$relatedProducts = ProductModel::find(1)->relatedProducts()->get();
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报
0/150
提交
取消