Reputation: 521
How can I get a record within my single table? I have multiple sub-types while still using single-table inheritance?
id | name | sex | city | type | created_at | updated_at
1 | Akira | female | Jaipur | user | 2014-08-30 | 2014-08-30
2 | Nick | male | Jaipur | admin | 2014-08-30 | 2014-08-30
3 | Sam | male | Delhi | user | 2014-08-30 | 2014-08-30
this is my single table for user and admin. I want to check the new record before insert. if an old record is user type then not insert again and user type only update record. but an old record is user type then they want to be an admin so I want to insert a new record with admin type. Like:- Sam is an old user but he want to be an admin so he insert a new record with admin type. but if sam again insert data with user type so I don't want to insert again.
id | name | sex | city | type | created_at | updated_at
1 | Akira | female | Jaipur | user | 2014-08-30 | 2014-08-30
2 | Nick | male | Jaipur | admin | 2014-08-30 | 2014-08-30
3 | Sam | male | Delhi | user | 2014-08-30 | 2014-08-30
4 | Sam | male | Delhi | admin | 2014-08-30 | 2014-08-30
using laravel eloquent relationship
Upvotes: 0
Views: 590
Reputation: 521
$data= $request->first_input_data;
$isDataExist=ParentProduct::where('name',$data['name'])->where('type','parent')->first();
if (empty($isDataExist))
{
$isDataExist= new ParentData();
}
$isDataExist->fill($mainProduct)->save();
return $isDataExist->id;
Same process with child type data another function.
Upvotes: 1
Reputation: 1942
Reference this doc, and add unique key to column name
in the table.
ALTER TABLE users ADD UNIQUE name (name);
Now, if you insert same name, you will get a duplicated key error, use raw query:
DB::insert(
'INSERT INTO users (name, sex, city, type) values (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE type=VALUES(type)',
['Sam', 'male', 'Delhi', 'admin']
);
Now, when insert new data and column name
is duplicated in the table, then update old record column type
.
By the way, you can use this package to alternative raw query.
Upvotes: 0
Reputation: 164
You can use Rule::unique to achieve your validation rule
$messages = [
'data.name.unique' = 'Given name and user type are not unique',
];
Validator::make($data, [
'data.name' => [
'required',
Rule::unique('users')->where(function ($query) use($name,$type) {
return $query->where('name', $name)
->where('type', $type);
}),
],
],
$messages
);
Upvotes: 0
Reputation: 131
Why do you need to insert another user on just the same user? I mean, if you want to change the type of user you can just update the type.
But maybe you have reason so maybe in your case you can use unique
in your validation
.
$this->validate($request,[
'name' => 'required|string|unique:[nameoftable],name,,,type,'.$request['userType'].'|max:50',
]);
This will check if the name already exist in the database with the same type you send in your request. Hope it helps.
Upvotes: 0