我有两个雄辩的模型模型用户和零售商。我想要创建一个新的模型“任务”,其中应该有一个字段"added_by“,可以表示用户或零售商。
我如何为Task创建迁移,以便有一个字段可以表示用户或零售商?
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->morphes('added_by');
$table->timestamps();
});
例如,如何创建引用用户的任务?
Task::create([
'product_id' => 1,
'added_by' => ????
]);
同样,当我得到一个雄辩的任务实例时,我如何知道added_by是在引用用户还是零售商呢?
发布于 2021-05-09 15:44:40
迁移的语法是$table->morphs(...)
,而不是$table->morphes(...)
。
$table->morphs('added_by')
将创建added_by_id
和added_by_type
列
备选案文1: 1-M多态关系
您需要在User
、Retailer
和Task
模型中定义一些关系
User
class User extends Authenticable
{
public function tasks()
{
return $this->morphMany(Task::class, 'added_by');
}
}
Retailer
class Retailer extends Model
{
public function tasks()
{
return $this->morphMany(Task::class, 'added_by');
}
}
Task
class Task extends Model
{
protected $fillable = ['product_id'];
public function added_by()
{
return $this->morphTo();
}
}
若要为User
或Retailer
添加一个Retailer
,请使用relationship方法。
$user->tasks()->create(['product_id' => $productId]);
$retailer->tasks()->create(['product_id' => $productId]);
选项2: M多态关系
另一种选择是在Product
与User
和Retailer
之间使用多到多的多态关系
您需要在User
、Retailer
和Product
节点中定义一些关系。
User
class User extends Authenticable
{
// Optional
public function tasks()
{
return $this->morphMany(Task::class, 'added_by');
}
public function products()
{
return $this->morphToMany(Product::class, 'added_by', 'tasks')
->using(Task::class)
->withTimestamps();
}
}
Retailer
class Retailer extends Model
{
// Optional
public function tasks()
{
return $this->morphMany(Task::class, 'added_by');
}
public function products()
{
return $this->morphToMany(Product::class, 'added_by', 'tasks')
->using(Task::class)
->withTimestamps();
}
}
Product
class Product extends Model
{
// Optional
public function tasks()
{
return $this->hasMany(Task::class, 'product_id');
}
public function users()
{
return $this->morphedByMany(User::class, 'added_by', 'tasks')
->using(Task::class)
->withTimestamps();
}
}
Task
use Illuminate\Database\Eloquent\Relations\MorphPivot;
class Task extends MorphPivot
{
public $incrementing = true;
// Optional
public function added_by()
{
return $this->morphTo();
}
// Optional
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
}
将User
或Retailer
与Product
相关联(使用Task
作为变形枢轴)
$user->products()->attach($productId);
$retailer->products()->attach($productId);
https://stackoverflow.com/questions/67459313
复制相似问题