繁体   English   中英

如何在Laravel 4中使用不带id的Eloquent更新数据

[英]How can I update data with Eloquent without id in Laravel 4

当我想更新FaqTrans数据库时,此数据集有两个主键(faq_ida和lang) $table->primary(array('lang', 'faq_id')); table- $table->primary(array('lang', 'faq_id')); 所以我不需要带有auto_increment的id列。

但是,当我使用以下代码更新数据库时,错误消息提示我没有id列。

$faq_trans = FaqTrans::where('faq_id','=',$faq_id)->where('lang','=',$lang)->first();
$faq_trans->lang  = Input::get('lang');
$faq_trans->body  = Input::get('body');
$faq_trans->title = Input::get('title');
$faq_trans->save();

错误信息

SQLSTATE [42S22]:找不到列: FAQtrans子句'中的未知列'id'(SQL:update FAQtrans set body =?, updated_at =?,其中id为null)(绑定:数组(0 =>'adfadaaadfadaa', 1 =>'2013-07-04 11:12:42',))

当我添加一个id列时,代码可以正常工作...

有什么方法可以更新没有ID列的数据库?

将此行写入模型

public $primaryKey = '_id';

_id是您的手动主键

Laravel / Eloquent不支持复合主键。

当您检查Eloquent Model类时,您会看到主键只能是一个字符串,用于创建WHERE子句。

很简单:

FaqTrans::where(
            [
                'faq_id' => $faq_id,
                'lang' => $lang
            ]
        )->update(
            [
                'body' => $body,
                'title' => $title
            ]
        );

对于将来遇到这个问题的人(就像我一样),这是Eloquent中复合主键的一个不错的解决方法。

这是模型类的顶部:

protected $primaryKey = array('key1', 'key2');

然后,您可以使用以下方法在模型上覆盖save()方法:

public function save(array $options = array())
{
    if(!is_array($this->getKeyName()))
        return parent::save($options);

    // Fire Event for others to hook
    if($this->fireModelEvent('saving') === false)
        return false;

    // Prepare query for inserting or updating
    $query = $this->newQueryWithoutScopes();

    // Perform Update
    if ($this->exists) {
        if (count($this->getDirty()) > 0) {
            // Fire Event for others to hook
            if ($this->fireModelEvent('updating') === false)
                return false;

            // Touch the timestamps
            if ($this->timestamps)
                $this->updateTimestamps();

            //
            // START FIX
            //

            // Convert primary key into an array if it's a single value
            $primary = (count($this->getKeyName()) > 1) ? $this->getKeyName() : [$this->getKeyName()];

            // Fetch the primary key(s) values before any changes
            $unique = array_intersect_key($this->original, array_flip($primary));

            // Fetch the primary key(s) values after any changes
            $unique = !empty($unique) ? $unique : array_intersect_key($this->getAttributes(), array_flip($primary));

            // Fetch the element of the array if the array contains only a single element
            $unique = (count($unique) <> 1) ? $unique : reset($unique);

            // Apply SQL logic
            $query->where($unique);

            //
            // END FIX
            //

            // Update the records
            $query->update($this->getDirty());

            // Fire an event for hooking into
            $this->fireModelEvent('updated', false);
        }

    // Perform Insert
    } else {
        // Fire an event for hooking into
        if ($this->fireModelEvent('creating') === false)
            return false;

        // Touch the timestamps
        if ($this->timestamps)
            $this->updateTimestamps();

        // Retrieve the attributes
        $attributes = $this->attributes;

        if ($this->incrementing && !is_array($this->getKeyName()))
            $this->insertAndSetId($query, $attributes);
        else
            $query->insert($attributes);

        // Set exists to true in case someone tries to update it during an event
        $this->exists = true;

        // Fire an event for hooking into
        $this->fireModelEvent('created', false);
    }

    // Fires an event
    $this->fireModelEvent('saved', false);

    // Sync
    $this->original = $this->attributes;

    // Touches all relations
    if (array_get($options, 'touch', true))
        $this->touchOwners();

    return true;
}

原始来源: https : //github.com/laravel/framework/issues/5517#issuecomment-52996610

更新2016-05-03

我最喜欢的新方法:

如何在Laravel 5中将组合键放在模型中?

转到您的FaqTrans模型并添加它。

public $key = 'faq_id';

假设faq_idlang更重要,就应该这样做

如果有人有同样的问题。 我用Nishchit Dhanani答案,它工作得很好这是: 写这行到你的模型
public $ primaryKey ='_id';
_id是您的手动主键

就我而言。 我有一个用户表,部分用户是学生。 因此,我的学生表中的主键是“ user_id”。
在我的学生模型中添加以下行:public $ primaryKey ='user_id';

更新学生对象时,我可以使用save()方法。

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM