2016-03-10 61 views
1

我有以下的票表自加盟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。

下面是票務型號

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

我想一票的所有子票證。但我得到空。

如果我缺少一些東西,你可以請指導。

回答

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

您將關係於是作品