php - 在 laravel 关系中设置外表的位置
问题描述
我有一张表与其他表有很多关系,但它与entity
价值分开,请看这个:
我有这个架构
public function up()
{
Schema::create('cards', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('entity_id');
$table->string('entity');
$table->integer('qty')->nullable()->default('1');
});
}
public function up()
{
Schema::create('tickets', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->string('summary');
$table->integer('amount');
$table->integer('stock')->default('0');
$table->integer('discount')->default('0');
});
}
public function up()
{
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('title');
$table->integer('amount');
$table->integer('discount');
$table->text('description');
$table->integer('stock')->default('0');
});
}
以及模型中的这种关系
class Card extends Model
{
protected $table = 'cards';
public $timestamps = true;
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
public function product()
{
return $this->belongsTo('App\Models\Product', 'entity_id');
}
}
我需要where entity = 'ticket'
在使用前进行设置,belongsTo
我的意思是一个表与许多表基的关系entity_id
,我按列和基数将它分开,entity
相同的 vlue 大多数只有现实。
解决方案
你可以简单地在你雄辩的模型文件中做。这样做:
public function ticketWithCondition()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id')->where('entity' , 'ticket');
}
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
像这样打电话:
// for show Card with EntityCondition
$comments = Card::find(123)->with('ticketWithCondition');
// for show comments without EntityCondition
$comments = Card::find(123)->with('ticket');
推荐阅读
- debugging - Amyuni“打印机未激活”错误是什么意思?
- reactjs - 如何启动和打开电子邮件客户端 ReactJS
- pandas - 带有缺失值的 Pandas 转换为 Int64
- javascript - TypeError:使用 spotify 的 api 时无法读取未定义的属性
- javascript - 试图从环境文件中检索值在反应 js 中未定义
- mysql - mysql - 从多个表中获取相关行而不使用所有组合
- jax-rs - JAX-RS Response.getEntity() 始终为空
- c# - C# 不能采用 Windows InstallDate (fe CIM_OperatingSystem)
- python - discord.py BS4 选择具有相同类名的第二个 div
- snowflake-cloud-data-platform - 如何在雪花日期数据类型字段中插入儒略日期