将相同的关系转移到核心
transfer the same relation to the core
我有 CoreModel 扩展自模型
class CoreModel extends Model
{
我扩展了 coreModel
中的所有模型
class Product extends CoreModel
大多数表都有一个 author_id 列属于 User
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id')->constrained('users')
在我必须创建的每个模型中
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
我需要这样的东西。这段关系你
我需要移动到 coreModel,但如果此模型在 protected $fillable
中具有 author_id,则它应该适用于条件
你有什么建议?
I was thinking about writing trait .but I still have to do it on every model use this trait
在这种情况下,使用特征提供了一种更简单的方法。
trait BelongsToUser
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
}
class Product extends Model
{
use BelongsToUser;
}
我也按照我说的使用了Trait @Bulent
trait Author
{
/**
* adding author_id
* @return void
*/
protected static function bootAuth(): void
{
static::creating(function ($query) {
$query->author_id = $query->author_id ?? auth()->id();
});
}
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
}
.
class Category extends Model
{
use Author;
我有 CoreModel 扩展自模型
class CoreModel extends Model
{
我扩展了 coreModel
中的所有模型class Product extends CoreModel
大多数表都有一个 author_id 列属于 User
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id')->constrained('users')
在我必须创建的每个模型中
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
我需要这样的东西。这段关系你
我需要移动到 coreModel,但如果此模型在 protected $fillable
你有什么建议?
I was thinking about writing trait .but I still have to do it on every model use this trait
在这种情况下,使用特征提供了一种更简单的方法。
trait BelongsToUser
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
}
class Product extends Model
{
use BelongsToUser;
}
我也按照我说的使用了Trait @Bulent
trait Author
{
/**
* adding author_id
* @return void
*/
protected static function bootAuth(): void
{
static::creating(function ($query) {
$query->author_id = $query->author_id ?? auth()->id();
});
}
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
}
.
class Category extends Model
{
use Author;