在Laravel 5.1中获取过滤和相关记录

时间:2015-12-20 12:02:01

标签: php laravel laravel-5 eloquent laravel-5.1

我有三个数据库表。

CREATE TABLE `tblprojecttype` (
  `ProjectTypeID` int(11) NOT NULL,
  `ProjectType` varchar(30) NOT NULL,
  `Description` varchar(500) NOT NULL,
  `IsActive` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tblprojecttypecurrencyprice` (
  `ProjectTypeCurrencyID` int(11) NOT NULL,
  `CurrencyID` int(11) NOT NULL,
  `ProjectTypeID` int(11) NOT NULL,
  `Price` decimal(10,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tblcurrency` (
  `CurrencyID` int(11) NOT NULL,
  `Currency` varchar(100) NOT NULL,
  `IsActive` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

模型

class Currency_Model extends Model
{
    protected $table = "tblcurrency";
    protected $primaryKey = "CurrencyID";
    public $timestamps = false;
}

class ProjectType_Model extends Model
{
    protected $table = "tblprojecttype";
    protected $primaryKey = "ProjectTypeID";
    public $timestamps = false;

    public function projecttypecurrencyprice()
    {
         return $this->hasOne('\App\Models\ProjectTypeCurrencyPrice_Model', 
                                                     "ProjectTypeID");
    }
}

class ProjectTypeCurrencyPrice_Model extends Model
{
    protected $table = "tblprojecttypecurrencyprice";
    protected $primaryKey = "ProjectTypeCurrencyID";
    public $timestamps = false;

    public function Currency()
    {
         return $this->belongsTo('\App\Models\Currency_Model', "CurrencyID");
    }
}

CurrencyID关系和ProjectTypeID关系

我在尝试什么?

在我的Laravel 5.1代码中,我试图在sql语句下面执行,以便我可以为每个projecttypecurrencyprice records获取ProjectType record。最后,它还应显示每个currency Table记录的projecttypecurrencyprice记录

$ProjectTypes = \App\Models\project\ProjectType\ProjectType_Model
                ::with("projecttypecurrencyprice")
                ->with("projecttypecurrencyprice.Currency")
                ->get();

问题是什么?

我正在获取每个projecttypecurrencyprice记录的所有货币记录。我只想要那些货币ID = 1

的货币

2 个答案:

答案 0 :(得分:0)

在获取相关的** projecttypecurrencyprice **对象时,您需要应用其他条件。您可以使用 whereHas()方法执行此操作。以下代码应该可以解决问题:

$ProjectTypes = \App\Models\project\ProjectType\ProjectType_Model
  ::with("projecttypecurrencyprice")
  ->with(["projecttypecurrencyprice.Currency" => function($query) {
    $query->where('CurrencyID', 1);
  }])
  ->get();

答案 1 :(得分:0)

如果我没有遗漏某些东西,不应该做一个简单的where() clause in your eloquent query builder伎俩吗?

像这样:

$ProjectTypes = \App\Models\project\ProjectType\ProjectType_Model
            ::with("projecttypecurrencyprice")
            ->with("projecttypecurrencyprice.Currency")
            ->where('id', 1)
            ->get();

(当然没有经过测试,请不要打我)