能否通过Eloquent为多对多表session_student与多态表prices建立关联?
可以通过Eloquent在session_student与prices之间添加关联
要实现这个关联,按以下步骤操作即可:
确保
session_student表包含多态关联所需字段:priceable_id(整数类型,存储关联模型ID)和priceable_type(字符串类型,存储关联模型的类路径)。如果没有这两个字段,需先通过迁移添加。为
session_student表创建Eloquent模型(默认多对多中间表通常没有模型,需手动创建):
namespace App\Models; use Illuminate\Database\Eloquent\Model; class SessionStudent extends Model { protected $table = 'session_student'; // 若表未包含created_at/updated_at字段,添加此行 public $timestamps = false; }
- 在
SessionStudent模型中定义与Price的多态关联:
public function price() { return $this->morphOne(Price::class, 'priceable'); }
- 在
Price模型中确保已定义反向多态关联:
public function priceable() { return $this->morphTo(); }
完成配置后,即可像使用其他Eloquent关联一样操作:
// 获取指定session_student记录对应的价格 $sessionStudent = SessionStudent::find(1); $price = $sessionStudent->price; // 为session_student记录创建关联价格 $sessionStudent->price()->create([ 'amount' => 99.99, // 其他price表字段 ]);
补充说明:session_student作为多对多中间表,只要为其创建Eloquent模型,就可以像普通模型一样定义各类关联(包括多态关联),这完全符合Eloquent的关联机制。
内容的提问来源于stack exchange,提问作者K i
相关产品推荐
相关产品推荐

