【问题标题】:store new entity with foreign relation存储具有对外关系的新实体
【发布时间】:2019-08-03 21:45:15
【问题描述】:

菜鸟问题:

我有一个名为“locations”的模型A,其中有一列名为“id”。 我有一个名为“资产”的模型B,它还有一个名为“id”的列。

在 ModelB 上,我想跟踪它与哪个位置相关联,因此我有一个名为“location_id”的列并设置了外键。

我的问题是......在我的 ModelB 控制器上......当我收到信息时,API 上的属性是否应该被称为“location_id”?因为我看到的只是将其命名为“locationId”而不带下划线。但这会产生一个问题,因为这不是该列的名称..

谢谢

尝试浏览有关雄辩关系的文档,但找不到任何可以回答我问题的内容。

【问题讨论】:

    标签: laravel foreign-keys


    【解决方案1】:

    考虑这个例子:

    class ModelB
    {
        protected $fillable = ['location_id', ...];
    
        public function location() 
        {
            // Assuming ModelA is a Location class.
            // The default parameters of belongsTo will search for `location_id`.
            // You can pass custom parameters if you have another column.
            return $this->belongsTo(ModelA::class);
        }
    }
    

    然后您可以使用ModelB::find(1)(获取 ID 1)或类似代码检索您的 ModelB。

    $model = ModelB::find(1);
    $location = $model->location;
    
    // These 2 calls return the same value, although the second one retrieves it through the relation,
    // which means an extra query is called if the `location` relation is not loaded yet.
    $locationId = $model->location_id;
    $locationId = $model->location->id;
    

    【讨论】:

      【解决方案2】:

      是的,您希望输入的字段名称尽可能与模型上的名称匹配(所以location_id)。这让生活变得更轻松,因为您可以直接从 $request 对象自动提取信息,匹配 db 字段等。

      因此,作为一个可能的示例,您可能有一个来自 Web 源(API、表单等)的字段,其中您有多个字段,包括 location_id。如果您的方法使用Request 对象进行拉取,您可以执行saveupdate,而无需更多代码:

        $newAsset = Asset::create($request->all());
      

      您可能会稍微混淆这一点的是相关位置资产模型上的方法或关系。您可能希望将此命名为location(不是id)。有了这个,您可以简单地从资产中提取位置:$asset->location->name

      HTH

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        • 2012-03-04
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        相关资源
        最近更新 更多