如何在Laravel 4中使用Eloquent无ID更新数据

时间:2013-07-04 03:27:52

标签: php laravel laravel-4 eloquent

当我想更新FaqTrans数据库时,此数据有两个主键(faq_ida和lang)$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]:未找到列:1054'where'中的未知列'id'   子句'(SQL:update FAQtrans set body =?,updated_at =?where   id为null)(Bindings:array(0 =>'adfadaaadfadaa',1 =>   '2013-07-04 11:12:42',))

当我添加id列时,代码工作正常......

有没有办法在没有ID列的情况下更新数据库?

6 个答案:

答案 0 :(得分:28)

将此行写入模型

public $primaryKey = '_id';

其中_id是您的手动主键

答案 1 :(得分:6)

Laravel / Eloquent不支持复合主键。

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

答案 2 :(得分:5)

非常简单:

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

答案 3 :(得分:5)

对于任何在将来偶然发现这个问题的人(就像我一样),这里是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

我最喜欢这样做的方法:

How I can put composite keys in models in Laravel 5?

答案 4 :(得分:1)

转到FaqTrans模型并添加此内容。

public $key = 'faq_id';

应该这样做,假设faq_idlang

更重要

答案 5 :(得分:-1)

如果有人有同样的问题。 我使用了Nishchit Dhanani的答案,它运作得很好,这是: 将此行写入您的模型中  public $ primaryKey =&#39; _id&#39 ;;
其中_id是您的手动主键

对于我的情况。我有一个用户表,我的部分用户是学生。所以我学生表中的主键是&#34; user_id&#34;。
在我的学生模型中添加此行:public $ primaryKey =&#39; user_id&#39;;

我在更新学生对象时能够使用save()方法。

希望这有帮助