duan89197 2014-02-11 17:04
浏览 30

许多Laravel 4使用基于字符串的主键

Given a few models trying to use Contact::sync(array(1,2,3)) to add mailing lists fails because the primary key email_address does not get filled out.

The table structure:

Contacts
    - email_address string (PK)
    - name          string

MailingLists
    - id    integer (PK)
    - name  string

ContactMailingLists
    - contact_id      string (PK, FK)
    - mailing_list_id integer (PK, FK)

And Models:

<?php

class MailingList extends Eloquent
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'mailing_lists';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function contacts ()
    {
        return $this->belongsToMany('\Application\Entity\Contact', null, 'id', 'email_address')->withTimestamps();
    }
}

class Contact extends Eloquent 
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'contacts';

    /**
     * @var string
     */
    protected $primaryKey = 'email_address';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function mailing_lists ()
    {
        return $this->belongsToMany('\Application\Entity\MailingList', null, 'id', 'mailing_list_id')->withTimestamps();
    }
}

When using ->sync() or other relational functions in eloquent it produces errors. The sync() method produces an error because on the insert the email_address is set to 0 instead of the email_address.

EDIT: Added the related keys to the code.

  • 写回答

2条回答 默认 最新

  • dpyu7978 2014-02-11 17:30
    关注

    You should pass the custom key when declaring the relation along with the pivot table name:

    public function mailing_lists ()
    {
        return $this->belongsToMany('\Application\Entity\MailingList', 'ContactMailingLists', 'email_address', 'MailingList_id')
                    ->withTimestamps();
    }
    

    Check the manual.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用