自我加入Laravel 5.2

时间:2016-03-10 04:07:47

标签: php laravel 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相关。

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

以下是我的查询

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

我正在尝试获取故障单的所有儿童票。但我得到了无效。

如果我错过了什么,请指导。

1 个答案:

答案 0 :(得分:4)

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

/*---------------------------------------------------------
 * 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关系。

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

你的关系会有效吗