Laravel 5.2中的自我加入 [英] Self Join in Laravel 5.2

查看:73
本文介绍了Laravel 5.2中的自我加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下票证表

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

主键是TicketID,还有另一列称为ParentTicketID,它与TicketID相关.

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

以下是故障单模型

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

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

以下是我的查询

$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.

推荐答案

这是我的示例代码,您可以尝试一下,希望对您有所帮助

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

已编辑

更新您的方法

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

像这样

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

并像这样更新您的查询模型,因为您已经获得了TicketReplies关系.

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

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

您的关系将开始工作

这篇关于Laravel 5.2中的自我加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆