Self Join in Laravel 5.2

前提是你 提交于 2019-12-20 04:22:39

问题


I have the following Ticket Table

if(!Schema::hasTable('tblticket')) {
    Schema::create('tblticket', function (Blueprint $table) {
        $table->increments('TicketID');
        $table->string('Subject', 50);
        $table->integer('ParentTicketID')->nullable()->unsigned();
        $table->timestamps();

        $table->foreign('ParentTicketID')->references('TicketID')->on('tblticket');
    });
}

Primary Key is TicketID and There is another column called ParentTicketID, which is related to TicketID.

Below is Ticket Model

class TicketModel extends Model
{
    public $table = 'tblticket';
    public $primaryKey = 'TicketID';
    public $timestamps = true;

    public function TicketReplies() {
        return $this->belongsTo('\App\Models\TicketModel', 'TicketID');
    }
}

Below is my Query

$Ticket = \App\Models\TicketModel
    ::with('TicketReplies')
    ->where('ParentTicketID', '=', $TicketID)
    ->first();

I am trying to get all child tickets of a Ticket. but I am getting null.

Can you please guide if I am missing something.


回答1:


this is my sample code, you can try this, I hope that will help you

/*---------------------------------------------------------
 * Relationship with same table, means recursive key
 * --------------------------------------------------------
 */


//this will get the childern against parent.

public function doseage_childs(){
    return $this->hasMany('App\Models\DoseageForm', 'parent_id', 'id');
}


//this will get the parent against childern

public function doseage_parent(){
    return $this->belongsTo('App\Models\DoseageForm', 'parent_id', 'id');
}

Edited

update your this method

public function TicketReplies() {
    return $this->belongsTo('\App\Models\TicketModel', 'TicketID');
}

like this

public function TicketReplies() {
    return $this->hasMany('\App\Models\TicketModel','ParentTicketID' ,'TicketID');
}

and update your query model like this, because you already getting TicketReplies relationships.

$Ticket = \App\Models\TicketModel
    ::with('TicketReplies')
    ->where('TicketID', '=', $TicketID)
    ->first();

You relationship will works then



来源:https://stackoverflow.com/questions/35907399/self-join-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!