部分比赛中的口才关系 [英] Eloquent Relationship on Partial Match

查看:66
本文介绍了部分比赛中的口才关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有一种雄辩的关系,其中联接上只会部分匹配吗?

Can I have an eloquent relationship where there will only be a partial match on the joins?

为了解释,这是一个模型;

To explain, here is one Model;

class PostcodeCoord extends Model {
  public function payment()
  {
    return $this->hasMany('App\Models\Payment', 'Vendor ZIP', 'postcode');
  }
}

还有其他型号;

class Payment extends Model {
  public function postcodeCoord()
  {
    return $this->belongsTo('App\Models\PostcodeCoord', 'postcode', 'postcode');
  }
}

我的payments表有一个名为Vendor ZIP的列.我的postcode_coords表中有一列称为postcode.

My payments table has a column called Vendor ZIP. And my postcode_coords table has a column called postcode.

问题在于,postcode列的长度仅为3或4个字符(英国邮政编码Eg SW1A的第一部分).而Vendor ZIP是完整的6或7个字符.例如SW1A2AA.

The problem, is that the postcode column is only 3 or 4 characers long (the first section of a UK postcode Eg SW1A). Whereas, Vendor ZIP, is the full 6 or 7 characters. Eg SW1A2AA.

推荐答案

AFAIK,无法在ID字段之间的部分匹配上创建关系.也就是说,我可以想到两种不同的解决方法:

AFAIK, there is no way to create a relationship on a partial match between the ID fields. That said, I can think of two different ways to solve this:

  1. payments表中添加一个名为postalcodegroup之类的新列.创建或更新模型时,请确保此列用邮政编码的第一部分填充.最好的方法是通过模型事件.然后,您可以在payments.postcodegrouppostcode_coords.postcode之间创建关系.

  1. Add a new column to your payments table called something like postalcodegroup. When the model is created or updated, ensure that this column is filled in with the first part of the postal code. The best way to do this would be via model events. Then you can create your relationship between payments.postcodegroup and postcode_coords.postcode.

在付款"模型上写一个访问者,在调用postcode_coords表时执行数据库查询以检索相关数据.

Write an accessor on the Payment model which will perform a database query to retrieve the relevant data from the postcode_coords table when it's called.

尽管在选项1中确实需要向表中添加列,但这两个选项中的选项1可能更好(更干净).

Of the two, option 1 is probably better (cleaner), although it does require adding columns to your tables.

这篇关于部分比赛中的口才关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆