Kousha
Kousha

Reputation: 36189

Laravel Eloquent - Find and Other queries

Why can't I use findwith other queries? I want to be able to say find something where id = 2 and otherColumn = thisValue. However, if I use find(2) and add the other query, then the sql query I get is where 'id' = ? and returns all ids. Why?!

Thanks

Upvotes: 1

Views: 1539

Answers (2)

The Alpha
The Alpha

Reputation: 146191

You can use find with other queries but you don't need to use other queries with find because find method query into database using the primary key and if you have one user with a primary key for example, id=1 then it couldn't be twice, means it must be unique and use of other queries with find is useless. The find method in Illuminate\Database\Eloquent\Model calls the find method of Illuminate\Database\Eloquent\Builder class and that method is given below:

public function find($id, $columns = array('*'))
{
    if (is_array($id))
    {
        return $this->findMany($id, $columns);
    }

    $this->query->where($this->model->getKeyName(), '=', $id);

    return $this->first($columns);
}

If you use something like this:

User::where('username', 'someuser')->find(1);

It'll work (find should be called at last, it calls first and first calls get) but it's not useful in this case; with find. Primary key could be any field; not only id and getKeyName retrieves it.

Upvotes: 1

Jonathan Chow
Jonathan Chow

Reputation: 703

find($id) automatically finds the record with the same value in your $primaryKey column, $primaryKey can be set in your model. If you wish to use other query, you should use where()

Your query should be like this:

Model::where('id','=',2)->where('otherColumn','=','thisValue')->get();

Upvotes: 0

Related Questions