在Laravel 5.1

时间:2015-12-15 10:01:08

标签: php laravel-5 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->hasOne('\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记录的货币记录。

1 个答案:

答案 0 :(得分:0)

对于ProjectTypeCurrencyPrice_Model,您应该以这种方式更改Currency关系:

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

因为您在CurrencyId中有tblprojecttypecurrencyprice列,并且您与ProjectTypeCurrencyPrice_Model中的tblcurrency没有任何关联。 并获取数据而不是:

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

您可以省略1st with

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

顺便说一下,如果你开始这个项目,你应该考虑数据库结构的变化,并阅读PHP中的PSR - 如果你真的没有,你不应该使用ProjectTypeCurrencyPrice_Model作为你的模型名称to,与MySQL中的ProjectTypeID列相同