【问题标题】:Navigating through models using relationships with Laravel and Eloquent使用 Laravel 和 Eloquent 的关系浏览模型
【发布时间】:2019-01-22 14:14:49
【问题描述】:

我正在做一个项目,我们有以下模型:

  • 项目类型
  • 项目子类型
  • 项目

作为一个例子,我会说:

ItemType:硬件或软件

ItemSubtype:RAM、电源(如果是硬件)或应用程序、操作系统(如果是软件)

项目:4GB DDR4(如果是 RAM)或 MS Office 2019(如果是应用程序)

这些是我看到的关系:

  1. 一个ItemType可以有多个ItemSubtype,而ItemSubtype只能属于一个ItemType
  2. 一个ItemSubtype可以有多个Item,而一个Item只能属于一个ItemSubtype

这些是我的问题:

  1. 显然,一个Item只能属于一个ItemType。我是否需要在 ItemItemType 模型之间建立关系?
  2. 如果问题1返回true(这是整天编码的结果!)我应该使用什么样的关系? ItemType 有很多 ItemItemSubtype (hasManyThrough)?还是 ItemType 有许多 ItemItem 属于一个 ItemType?或者只是使用 ItemSubtype 作为中间模型,并通过 ItemSubtypeItemItemType 并通过反之亦然,没有任何ItemTypeItem 之间的直接关系?
  3. 如果我不创建 ItemType 之间的关系,我是否需要在 items 迁移中使用 item_type_id >项目模型?

  4. 有不同的方法吗?

提前谢谢你!

【问题讨论】:

  • ItemType has many Item through ItemSubtype... 是吗?似乎您在 Item 实体中有一个 item_type_id。那将是一个简单的 HasMany。
  • 我看到你在问题 3 中问过这个问题。由于我们不知道应用程序的要求,因此很难回答其中一些问题。这里唯一真正的问题是您是否需要在不处理 ItemSubtype 的情况下从 ItemType 中辨别出 Items,反之亦然。如果您只是从 itemsubtype 中辨别项目,那么为什么需要 items 和 itemtype 之间的关系?这是一个设计决策,我们无法真正回答。
  • @Devon 清楚!如果我决定需要直接从 ItemType 中辨别 Items,我应该选择什么? HasManyThrough 并从项目迁移中删除 item_type_id 或保留它并在 ItemType 上使用 hasMany?
  • 这取决于你。数据库规范化将决定 HasManyThrough,但 Laravel 没有 BelongsToThrough 关系(反之),所以如果您决定需要它并且不想要复杂的查询,您可能想要反规范化并在 items 表中拥有 item_type_id。
  • @Devon Dude,你的答案是正确的!非常感谢!

标签: laravel eloquent-relationship


【解决方案1】:

您可以轻松做到这一点:

dd($rental_obj->car->maker->make_name); // output : VolksWagen

如果你的模型写得很好:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @property integer $id
 * @property integer $id_renter
 * @property integer $id_car
 * @property float $price
 * @property Date $date_beg
 * @property Date $date_end
 * @property Car $car
 * @property Renter $renter
 * @property string $created_at
 * @property string $updated_at
 */
class Rental extends Model
{
    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'integer';

    /**
     * @var array
     */
    protected $fillable = ['id_renter','id_car','price','date_beg','date_end'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function car()
    {
        return $this->belongsTo('App\Models\Cars', 'id_car');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function renter()
    {
        return $this->belongsTo('App\Models\Renters', 'id_renter');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-26
    • 2021-10-01
    • 2018-10-20
    • 2021-07-04
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多