【发布时间】:2021-03-11 21:30:49
【问题描述】:
我有很多表如下
植物:模型
public function species()
{
return $this->belongsToMany(Species::class,'phyto_species')->withPivot(['destination_id',
'preservation_id','weight']);
}
物种:模型
public function phytos()
{
return $this->belongsToMany(Phyto::class,'phyto_species')->withPivot(['destination_id',
'preservation_id','weight']);
}
数据透视表
public function up()
{
Schema::create('phyto_species', function (Blueprint $table) {
$table->id();
$table->integer('phyto_id')->unsigned();
$table->integer('species_id')->unsigned();
$table->integer('destination_id')->unsigned();
$table->integer('preservation_id')->unsigned();
$table->double('weight', 8,2);
// $table->double('charge', 8,2);
$table->softdeletes();
$table->timestamps();
});
}
我的另外两个查找表的目的地和保存如下
public function up()
{
Schema::create('destinations', function (Blueprint $table) {
$table->id();
$table->string('destination_name');
$table->softdeletes();
$table->timestamps();
});
}
public function up()
{
Schema::create('preservations', function (Blueprint $table) {
$table->id();
$table->string('preservation_name');
$table->softdeletes();
$table->timestamps();
});
}
我的问题是我能够显示重量、物种名称保存 ID 和目的地 ID,但我不想显示保存 ID 和目的地 ID,而是显示保存名称和目的地名称
@foreach ($phyto->species as $item)
<ul>
<li>
{{$item->pivot->weight}} {{$item->species_name}} {{$item->pivot->preservation_id}} {{$item->pivot->destination_id}}
</li>
</ul>
@endforeach
我可以使用下面显示的 sql 查询来获取保存名称和目的地名称,但我正在寻找在关系中使用函数的其他方法
select phytos.customer_name, phytos.phyto_number, phyto_species.weight,
preservations.preservation_name, destinations.destination_name from phytos
left join phyto_species on phytos.id = phyto_species.phyto_id left JOIN
destinations on destinations.id = phyto_species.destination_id left JOIN
preservations on preservations.id = phyto_species.preservation_id limit 5
请帮忙!
【问题讨论】:
标签: laravel