如何在拉拉威尔组上表演有很多

  • 本文关键字:表演 php laravel
  • 更新时间 :
  • 英文 :


我有两个表,

buyers

类型
字段
id bigint unsigned
名称 varchar(255(

正如您所说,买家可以有多个zip&因此,一个zip可以有多个买家。这不是一对多的关系。这实际上是多对多关系,因此您需要更改模型和关系并使用透视表。

买方型号:

use AppModelsZip;
class Buyer extends Model
{
use HasFactory;
public function zips() {
return $this->belongsToMany(Zip::class);
}
} 

Zip型号

use AppModelsBuyer;
class Zip extends Model
{
use HasFactory;
public function buyers() {
return $this->belongsToMany(Buyer::Class);
}
}

数据透视表迁移:

return new class extends Migration
{
public function up()
{
Schema::create('buyer_zip', function (Blueprint $table) {
$table->id();
$table->foreignid('buyer_id')->constrained();
$table->foreignid('zip_id')->constrained();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('buyer_zip');
}
};

然后你可以很容易地与相关买家获得Zip:

Zip::with('buyers')->get();

尝试删除生成器中的groupBy。就这样吧:

BuyerZip::with('buyers')->get()

尝试此代码

BuyerZip::with('buyers')->groupBy('buyer_id')->all()

最新更新