[英]set where for foriegn table in laravel relation
I have a table has many relation to other tables but it seperated with entity
value please look at this : 我有一个与其他表有很多关系的表,但它与
entity
值分开,请查看:
i have this schema 我有这个架构
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');
});
}
and this relation in models 和模型中的这种关系
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');
}
}
i need to set where entity = 'ticket'
before use belongsTo
i mean is a table hase relation to many table base entity_id
and i seperated it by entity
column and base same vlue most have realation just. 我需要先设置
where entity = 'ticket'
在使用belongsTo
之前,我的意思是表与许多表具有基本的entity_id
关系,并且我按entity
列将其分开,并且基本相同的vlue仅具有实现作用。
You can do simply in your eloquent model file. 您可以简单地在雄辩的模型文件中进行操作。 do like this :
这样做:
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');
}
call like this : 像这样打电话:
// for show Card with EntityCondition
$comments = Card::find(123)->with('ticketWithCondition');
// for show comments without EntityCondition
$comments = Card::find(123)->with('ticket');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.