簡體   English   中英

與Laravel一起使用Eloquent的ORM的最佳方法?

[英]Best way to apply Eloquent's ORM with Laravel?

我有兩個表:

treatments (
id,
name
)

companies (
id,
name
)

我需要建立與“價格”表的關系。 我想到以下內容:

prices (
treatment_id,
company_id,
price
)

但是我不知道如何將ORM應用於php應用程序。 我正在將Laravel與Eloguent的ORM一起使用。 我認為真正的問題是這是否是設計數據庫的好方法。 也許我應該使其與眾不同? 有什么建議嗎? 謝謝,班

如果一家公司可以有多種治療,並且可以以不同的價格從多個公司購買治療,那么您將具有多對多關系,而prices是數據透視表(如果您遵守約定,則將其命名為company_treament ,但這不是必須的)。 因此,您需要為TreatmentsCompanies建立兩個模型,如下所示:

class Company extends \Eloquent {

    public function treatments()
    {
        return $this->belongsToMany('Treatment', 'prices')->withPivot('price');
    }

class Treatment extends \Eloquent {

    public function companies()
    {
        return $this->belongsToMany('Company', 'prices')->withPivot('price');
    }
}

模型中的treatments()companies()方法負責獲取相關項目。 通常, hasMany方法僅將相關模型作為第一個參數,但是在您的情況下,數據透視表名稱是非標准的,並且通過將其作為第二個參數傳遞而設置為prices 同樣通常對於數據透視表,僅會提取關系列( treatment_idcompany_id ),因此您需要使用withPivot指定額外的列。 因此,如果您想獲得一家ID為1的公司的待遇,您應該這樣做:

$treatments = Company::find(1)->treatments;

反之亦然:

$companies = Treatment::find(1)->companies;

如果您需要訪問任何這些關系的價格,可以這樣做:

foreach ($treatments as $treatment)
{
    $price = $treatment->pivot->price;
}

您可以在Laravel文檔中閱讀有關如何使用Eloquent實現關系的更多信息。

編輯

要在數據透視表中插入一個關系條目,可以使用attach並使用detach刪除一個(有關更多信息,請閱讀Docs )。

$treatment->companies()->attach($companyId, array('price' => $price));
$treatment->companies()->detach($companyId);

要更新數據透視表條目,請使用updateExistingPivot

$treatment->companies()->updateExistingPivot($companyId, array('price' => $price));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM