首页 > 解决方案 > 在 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 大多数只有现实。

标签: phplaravelrelation

解决方案


你可以简单地在你雄辩的模型文件中做。这样做:

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');

推荐阅读