2016-03-10 60 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(); 

您将关系于是作品