php - 具有基于字符串的主键的多对多 Laravel 4

标签 php laravel-4 eloquent

考虑到一些模型尝试使用 Contact::sync(array(1,2,3)) 添加邮件列表失败,因为主键 email_address 未填写。

表结构:

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)

和型号:

<?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();
    }
}

当在 eloquent 中使用 ->sync() 或其他关系函数时,它会产生错误。 sync() 方法会产生错误,因为在插入时 email_address 设置为 0 而不是 email_address。

编辑:将相关键添加到代码中。

最佳答案

将模型设置为不再尝试自动递增主键。

将其添加到任何没有自动递增键(例如 email_address)的模型上。

public $incrementing = false;

关于php - 具有基于字符串的主键的多对多 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708269/

相关文章:

html - 如何在mysql数据库中保存和搜索内容(使用wysiwyg html编辑器制作)?

php - 如何在 Laravel 4 中手动创建一个新的空 Eloquent 集合

php - Laravel 在哪里存储 memcached session 驱动程序的配置?

php - MySQL - 通过引用同一表的外键对记录进行排序/分组(Laravel,ORM)

php - 使用集合值获取 Laravel 集合的项目

php - Json 到带有希腊字符的 xml

php - 如何在 PHP 中创建 Word 文档页眉/页脚

php - 将 POST 数据从 Objective-C 传递到 PHP

javascript - 自动完成搜索的说明 - Laravel

php - Eloquent sortBy() 访问器不排序