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

28,318

Solution 1

Laravel / Eloquent doesn't support composite primary keys.

When you check the Eloquent Model class, you can see that the primary key can only be a string, which is used to create the WHERE clause.

Solution 2

Write this line into your Model

public $primaryKey = '_id';

Where _id is your manual primary key

Solution 3

Pretty simple:

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

Solution 4

For anyone who stumbles upon this question in the future (like I did), here's a nice workaround for a composite primary key in Eloquent.

This goes at the top of your model class:

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

Then you override the save() method on your model with this:

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;
}

Original source: https://github.com/laravel/framework/issues/5517#issuecomment-52996610

Update 2016-05-03

My new favorite way to do this:

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

Solution 5

Go to your FaqTrans model and add this.

public $key = 'faq_id';

That should do it, assuming faq_id is more important than the lang

Share:
28,318
Eugene Wang
Author by

Eugene Wang

Updated on May 10, 2020

Comments

  • Eugene Wang
    Eugene Wang almost 4 years

    When I want to update the FaqTrans database, but this datase have two primary key (faq_ida and lang) $table->primary(array('lang', 'faq_id'));. so I don't need a id column with auto_increment.

    However, when I use the following code to update the database, the error message hint me there is no id column.

    $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();
    

    error message

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update FAQtrans set body = ?, updated_at = ? where id is null) (Bindings: array ( 0 => 'adfadaaadfadaa', 1 => '2013-07-04 11:12:42', ))

    and when I added an id column, the code works fine...

    are there any way can I update the database without ID column ?

  • ftrotter
    ftrotter almost 10 years
    I think it is now $primaryKey according to this: laravel.com/docs/eloquent#basic-usage
  • Nathan Tuggy
    Nathan Tuggy almost 7 years
    Just upvote answers you find helpful, rather than writing other answers to repeat them.
  • Misagh Laghaei
    Misagh Laghaei over 5 years
    Nice and easy...!
  • Lonare
    Lonare over 2 years
    This does not work in Laravel 8.x.x as it will through an error saying : need string provided array.