繁体   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