【问题标题】:How do I make a hasOne relationship reference an attribute on the model instead of the primary key?如何使 hasOne 关系引用模型上的属性而不是主键?
【发布时间】:2013-10-01 17:39:30
【问题描述】:

在定义关系时,如何告诉 hasOne 模型使用模型的属性而不是 id 来连接?

我的课程是:

Site
  id
  zipcode

LocationData
  id
  zipcode

当我跑步时:

$site = Site::find(1);
$site->locationData

生成的查询是:

select * from `location_data` where `location_data`.`zipcode` = 1 limit 1

请注意,所引用的邮政编码列传递了 1(站点 ID),但我希望它使用站点的邮政编码。

注意:我不是在问如何在子关系上设置外键,而是如何将外键传递给父主键以外的属性。

【问题讨论】:

    标签: model laravel laravel-4 relationship eloquent


    【解决方案1】:

    知道了。这是一个调整:

    编辑您的模型并将 primaryKey 移至公共可见性:

    class Site extends Eloquent {
    
        public $primaryKey = 'id';
    
        ....
    }
    

    那么你只需要在需要的时候设置它:

    $site = Site::find(1);
    $site->primaryKey = 'zipcode';
    $site->locationData;
    

    【讨论】:

    • 这就是我在上面的“注释”部分中所指的内容。这告诉查询将邮政编码视为子模型上的外键,但这不是我要问的。我在问如何传递外键(邮政编码)而不是父模型的主键。
    【解决方案2】:

    您可以在定义关系时声明关系键。

    return $this->hasMany('Thing','key_to_use');
    

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2020-01-12
      • 2016-05-20
      • 2023-02-16
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多