2017-02-06 42 views
0

如何創建hasMany自我關係與哪裏標準?Laravel hasMany self where where criteria?

例如,這就是我想做的事:

class Payment extends \Illuminate\Database\Eloquent\Model { 
    public function refunds() { 
     return $this->hasMany(self::class, 'transaction_id', 'transaction_id') 
      ->where('this.method','=','that.method') 
      ->where('that.amount','<',0); 
    } 
} 

但我不知道如何給表中的兩個不同的別名,這樣我可以設置WHERE條件。

N.B.在我的例子中,「退款」只是一種負面支付。他們將擁有相同的交易ID和方法。

回答

0

如何構建你自己的HasMany類?

use Illuminate\Database\Eloquent\Relations\HasMany; 
use Illuminate\Database\Eloquent\Model; 

class Payment extends Model 
{ 
    public function refunds() { 
     $fKey = 'transaction_id'; 
     $instance = new static; 
     $instance = $instance->newQuery() 
         ->where('this.method','=','that.method') 
         ->where('that.amount','<',0);  

     return new HasMany(
      $instance, $this, $instance->getTable().'.'.$fKey, $fKey 
     ); 
    } 
} 
+0

你如何設置'this'和'that'別名? 'this'應該是當前的模型,''應該是相關的模型。 – mpen

0

你可以設置你的關係正常,並把情況在控制器

$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){ 
      $q->where('gender', 'Male'); 
     })->get(); 
+0

你將如何設置配置文件的別名,以便我可以正確地執行where條件? – mpen

+0

您必須在您的父模型中設置關係,以便您可以調用該關係模型拋出父模型 '''public function user() { return $ this-> belongsTo(User :: class); }''' –