截至目前我有2個不同的ModelProductModel.php這是我的產(chǎn)品清單。ProductRelated.php這是每個特定產(chǎn)品分配的相關產(chǎn)品。場景是,如果我id = 1的ProductModel.id (primary key of Product Model)在我的ProductRelated.php我有這個prodID(這相當于id (primary key of Product Model) 這將用于識別相關產(chǎn)品被分配的特定產(chǎn)品 ID。prodRelatedID這是與該產(chǎn)品相關的產(chǎn)品。所以我ProductModel會有這些數(shù)據(jù) 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遺囑中有這些數(shù)據(jù) 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條經(jīng)驗 獲得超5個贊
如果您只想獲取每個特定產(chǎn)品的所有相關產(chǎn)品,我認為您不需要ProductRelated
。
在你的ProductModel
public function relatedProducts() { return $this->belongsToMany(ProductModel::class, 'product_related', 'prodID', 'prodRelatedID'); }
然后你應該能夠獲取所有記錄,如下所示:
$relatedProducts = ProductModel::find(1)->relatedProducts()->get();
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消