I try to update field rate in table by primary key user_id.
So, I need to increment of decrement rate field. If row is not exist I need to create it.
I tried:
$this->point = -1; // Or $this->point = 1;
Rating::updateOrCreate(["user_id", $id], ["rate" => $this->point]);
But it does not work:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `rating` where (`0` = user_id and `1` = 5) limit 1)
This is because your passing the column and the value as two separate values.
Change:
["user_id", $id]
to:
["user_id" => $id]
Hope this helps!
Laravel (eloquent) provides a fluent way to update related models.
Assuming the following model structure:
Rating.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function ratings()
{
return $this->hasMany('App\Rating');
}
You can easily update the relation via associate()
$user = User::findOrFail($userId);
$rating = Rating::findOrFail($ratingId);
$rating->user()->associate($user)->save();
Read more about Relationships in Eloquent
Related
i have pivot table call user_privilege,
user_id,
privilege_id
house_group_id,
i use method sync for store data into pivot tabl, this is my method
$data = $this->getCollectedData($getListCollectData, $viewType, $data);
$getData = $this->crud->store($data);
$getData->getPrivilege()->sync([
'user_id' => $getData->id,
'house_group_id' => $this->request->get('house_group_id'),
'privilege_id' => 3,
]);
this is my getPrivilege() method in Users Model
public function getPrivilege()
{
return $this->belongsToMany(Privilege::class, 'user_privilege', 'user_id', 'privilege_id', 'house_group_id');
}
but when i click submit, return error like this
SQLSTATE[HY000]: General error: 1364 Field 'house_group_id' doesn't have a default value (SQL: insert into `user_privilege` (`privilege_id`, `user_id`) values (b3f08343-a8f6-4a45-b7bc-b396125634d3, ?))
when i dd($this->request->get('house_group_id')) return ID house_group_id like this
"2539d741-1526-4c42-b57a-da60e2e862d8"
this is UUID from house_group_id,
Whats wrong in My Code, how to save data with addtional pivot table ?
thanks
I have User Model with Roles relationships like so :
public function users(){
return $this->belongsToMany(User::class)->withTimestamps();
}
And Role Model with user relationships :
public function roles(){
return $this->belongsToMany(Role::class)->withTimestamps();
}
And of course Pivot Table "role_user" contains id, user_id, role_id and timestamps
I try to get users ordered By roles name like so :
$users = App\Models\User::with('roles')->orderBy('roles.name', 'desc')->get();
but i have this error :
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.name' in 'order clause' (SQL: select * from `users` where `users`.`deleted_at` is null order by `roles`.`name` desc)
http://localhost:8000/users
Please, some helps .
Try Like this:
$users = App\Models\User::with('roles')->get();
// order of the roles
$array = ['User','Admin','Doctor', 'Manager'];
$sorted = $users->sortBy(function($model) use ($array) {
return array_search($model['roles'], $array);
});
Hope it will help you!
I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'books.id' in
'where clause' (SQL: select * from books where books.id =
98745632564 limit 1)
when I pass id value as id. I have column name bookID in my database but in the above error it is comparing books.id = 98745632564. I could not understand where book.id is coming from.
public function showBook($id){
$book = Book::findOrFail($id);
return $book;
}
The code works perfectly fine when I pass id value with the query as follows
public function showBook($id){
$book = Book::where('bookID', $id)->find();
return $book;
}
You should set:
protected $primaryKey = 'bookID';
in your Book model to make:
$book = Book::findOrFail($id);
version work.
Methods find or findOrFail are using primary key and this is by default set to id, so if you have any custom primary key, you should set it in your Eloquent model.
From the Laravel documentation - if I have this many-to-many polymorphic relationship:
class Tag extends Eloquent {
public function posts()
{
return $this->morphedByMany('Post', 'taggable');
}
public function videos()
{
return $this->morphedByMany('Video', 'taggable');
}
}
So I can do this:
$tag = Tag::find(1);
$posts = $tag->posts;
$videos = $tag->videos;
How could I get all the tags relationships as one result? i.e. in a one-to-many polymorphic relationship you do this:
$tag = Tag::find(1);
$taggable = $tag->taggable;
But that doesnt seem to work for me in the many-to-many relationship - I get this SQL error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tag_groups.'
in 'where clause' (SQL: select * from tag_groups where
tag_groups.`` is null limit 1)
You'll have to merge the results yourself:
$taggable = $tag->posts->toBase()->merge($tag->videos);
This'll return an instance of Illuminate\Support\Collection.
An Eloquent collection does not make sense in this context.
You can't get all relations in one result but you may load them all eagerly using something like this:
$tag = Tag::with(['posts', 'videos'])->find(1);
$relations = $tag->getRelations();
Here $tag->getRelations() will return an array of loaded relations so you may access one using something like this:
$posts = $relations['posts']; // Collection of Post models
$videos = $relations['videos']; // Collection of Video models
You can merge them like:
$allRelations = array_merge($posts->toArray(), $videos->toArray());
Or using merge method of Illuminate\Support\Collection (As Joseph Silber mentioned)
$allRelations = $relations['posts']->toBase()->merge($relations['videos']);
In Eloquent, I know it's possible to define the table on runtime with $model->setTable().
I tried adding a new item in the constructor like:
$myModel = new \MyModel(array(), 'my_primary_key');
$myModel->setTable('mytable');
with the constructor being:
class MyModel extends Eloquent {
public function __construct($attributes = array(), $primaryKey = 'id') {
parent::__construct($attributes); // Eloquent
$this->primaryKey = $primaryKey;
}
}
That makes my $primaryKey = 'id' like the default.
- This one doesn't work cause it doesn't change the primaryKey to whatever I define in my call the constructor, it just gets the default ('id'). If I don't set a default I get the following error:
Missing argument 3 for MyModel::__construct(), called in
/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 517 and defined
I also tried:
$myModel->setAttribute('primaryKey', 'my_primary_key');
But this one doesn't set the attribute
But nothing works. The default for Laravel is having 'id' as the primaryKey, but in my tables I have things like 'car_id' for table Cars, and so on, so I get errors like:
Column not found: 1054 Unknown column 'id' in 'where clause'
(SQL: select * from `cars` where `id` = 1 limit 1)
I tried to look into the code: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L1415, but it doesn't have a method to set it on runtime.