ActiveRecord - 将外键与不同的命名约定相关联?
我正在使用 PHP-ActiveRecord ORM 开发一个私人消息系统。我有名为“User”和“Message”的模型,名为“users”和“messages”的 MySQL 表,在 messages 表中,有名为“sender_id”和“recipient_id”的字段。但是,我不知道如何将发件人和收件人正确关联到用户模型。
这是我迄今为止在用户模型中所拥有的:
static $has_many = array(
array('messages'),
array('recipients', 'foreign_key' => 'recipient_id', 'class_name' => 'Message'),
array('senders', 'foreign_key' => 'sender_id', 'class_name' => 'Message'),
);
这也是我迄今为止在消息模型中所拥有的:
static $belongs_to = array(
array('sender', 'class_name' => 'User'),
array('recipient', 'class_name' => 'User'),
);
但是,当我运行诸如 $message->recipient->first_name 之类的代码时,它无法正确拉取用户模型中的名字,就像我想要的那样。我不确定我做错了什么。
通常,我只使用标准命名约定。然而,对于这个例子,我们必须有sender_id和recipient_id,它们都是相同的类型,所以我不能像我一直在做的那样只使用标准命名约定。
任何帮助将不胜感激。我正在使用 PHP-ActiveRecord ORM。我认为 Rails 版本使用更广泛,但据我了解,除了语法不同之外,它们的工作原理相同。
I am working on a private messaging system using PHP-ActiveRecord ORM. I have models called 'User' and 'Message', MySQL tables called 'users' and 'messages', and in the messages table, I have fields called 'sender_id' and 'recipient_id'. However, I have no idea how to properly associate senders and recipients to the User model.
This is what I have so far in the User model:
static $has_many = array(
array('messages'),
array('recipients', 'foreign_key' => 'recipient_id', 'class_name' => 'Message'),
array('senders', 'foreign_key' => 'sender_id', 'class_name' => 'Message'),
);
and this is what I have so far in the Message model:
static $belongs_to = array(
array('sender', 'class_name' => 'User'),
array('recipient', 'class_name' => 'User'),
);
However, when I run the code such as $message->recipient->first_name, it does not properly pull the first name from the User model, like I want it to. I am not sure what I am doing wrong.
Normally, I just use the standard naming conventions. However, for this example, we have to have sender_id and recipient_id, which are both the same type, so I can't just use the standard naming conventions as I have been doing.
Any help would be highly appreciated. I am using the PHP-ActiveRecord ORM. I think the Rails version is more widely used, but it is my understanding that they work the same except with different syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还需要在 $belong_to 中指定外键,否则它们将从表的名称(即
user_id
)中推断出来:You also need to specify the foreign keys in the $belong_to, otherwise they will be inferred from the table's name (i.e.
user_id
):