I want to get all data in one column of the database (primary key) so that before I insert my data that is going to be inserted, I can check if its going to be duplicate or not.
Model:
public function getKeys() {
$this->db->select("key");
$this->db->from("database");
$result = $this->db->get();
return $result->result();
}
Controller:
public function Controler() {
$values = $this->MODEL_NAME->getKeys();
foreach ($values as $value) {
$array[] = $value->key;
}
# Compare new item to the current array
if (!(in_array($NEWITEM, $array))) {
# Insert
} else {
# Error catching
}
}
At insert time get all data from table.and then use condition on a particular field by which you want to check this data is already exist or not:
Related
mt_rand() and random_int() both are generate only one numbe and insert it in database where the number is already exist. I want to clear that , I want to insert a random number that is not exist in database.
I took this code from here
In my case in laravel 8, the code looks like below
public function generateProductCode() {
$number = mt_rand(1000000000, 9999999999);
// call the same function if the barcode exists in Dtabase already
if ($this->productCodeExists($number)) {
return $this->generateProductCode();
}
// otherwise, it's valid and can be used
return $number;
}
public function productCodeExists($number) {
// query the database and return a boolean
// for instance, it might look like this in Laravel
return Product::where('product_code', $number)->exists();
}
The model name is Product and DB table name is products. 'product_code' is the column where I want to do this query.
In store function where I Call generateProductCode() function, it looks like below
public function store(Request $request)
{
$product = new Product;
//Generate a Product key
$product->product_code = $this->generateProductCode();
$product->save();
}
It returns all time only one numbers that is 2147483647 .
Photo is here
What is the wrong? What is the perfect query to check exist so that it returns another that is not exist in the database.
You should create a recursion function check if the number is already used or not.
public function store(Request $request)
{
$product = new Product;
//Generate a Product key
$product->product_code = $this->newRandomInt();
$product->save();
}
private function newRandomInt()
{
$number = random_int(1000000000, 9999999999);
$isUsed = Product::where('number', $number)->first();
if ($isUsed) {
return $this->newRandomInt();
}
return $number;
}
according to php doc:
mt_rand: This function does not generate cryptographically secure
values, and should not be used for cryptographic purposes
you can use random_int
it Generates cryptographic random integers that are suitable for use where unbiased results are critical
$number = random_int(1000000000, 9999999999);
I have id(Primary key) of country in multiple tables and I want to check if its value exists or not in another referenced table.
Tried using the below code but I don't think this is the right way. Can anyone please suggest something...
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::select("select count(*) from country where ? not in (?)",[$id,$state]);
if($country == 0)
{
//
}
else{
//
}
}
You can check if a relationship for a record is present (or exists), using exists.
Assuming you have a relationship on your Country model called states:
public function states
{
return $this->hasMany(State::class);
}
You can check if a Country has any States related to it in your database.
// returns true if there are related states, otherwise false
Country::first()->states()->exists();
You can use whatever filtering criteria you want, so rather than first() you could use find($id) or where('field', $value) etc.
Use Exists Method here
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::table('country') //table set
->whereIn('column_name',$state) //if array then used whereIn method
->where('column_name',$id) //if single value use where method
->exists();
if($country)
{
//
}
else{
//
}
}
Im new in Laravel. I want to update my leaves pivot table. I am trying with below code but it only updates the single row i have multiple rows in db with same leave_id and i want to update all this where leave_id = xyz
I have following function in my model Leave:
public function relLeave(){
return $this->belongsToMany(User::class)->withPivot('days');
}
LeaveController:
public function saveUpdate(Request $request)
{
$leave = Leave::find($request->id);
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get()->first();
$msg->pivot->days = $request->days;
$msg->pivot->save();
}
I followed #option's instruction and it works for me i removed the first();
below is my updated code.
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get();
foreach($msg as $msgs)
{
$msgs->pivot->days = $request->days;
$msgs->pivot->save();
}
you can update extra fields in pivot table when updating relationship
$leave->relLeave()->sync([$request['id'] => ['days' => $request['days']]]);
You can use Query Builder for that if it's an option:
DB::table('leave_user')->where('leave_id', $request->id)->update(['days' => $request->days]);
This is just one DB query and it's pretty simple one.
If you want Eloquent solution, use updateExistingPivot() in a loop:
$leave = Leave::find($request->id);
$usersIds = $leave->relLeave()->pluck('id')->toArray();
foreach ($usersIds as $userId) {
$leave->relLeave()->updateExistingPivot($userId, ['days' => $request->days]);
}
Hello I have those 4 tables:
Products (id, name)
Params (id, name)
Product_Param (id, product_id, param_id)
Values (product_param_id, value)
I can get all product params:
public function params() {
return $this->belongsToMany('App\Models\Param', 'product_param')->withPivot('id', 'type1_id', 'type2_id');
}
Code:
foreach($products->params as $param) {
var_dump($param)
}
And now I need to get param value.
I wrote stupid code like this:
public static function getPPV($product_id, $param_id) {
$value = new \App\Models\ParamValue();
$value->value = NULL;
$value->id = NULL;
$pp = \App\Models\ProductParam::where('product_id','=',$product_id)->where('param_id','=',$param_id)->first();
if (!$pp) return $value;
$ppv = \App\Models\ProductParamValue::where('product_param_id','=',$pp->id)->first();
if (!$ppv) return $value;
$value->value = $ppv->productvalue->value;
$value->id = $ppv->productvalue->id;
return $value;
}
It works but I want use better solution with ORM. Param model:
public function val() {
$p = $this->hasOne('App\Models\ProductParam')->orderBy('id','desc')->where('product_id','=',$this->product_id);
$ppv = $p->getResults()->hasOne('App\Models\ProductParamValue');
$val = $ppv->getResults()->belongsTo('App\Models\ParamValue','param_value_id');
return $val;
}
But in Param Model I can't get Product ID ->where('product_id','=',$this->product_id) (we have Product_Param (id, product_id, param_id) and I get all rows from Product_Param.
Please help to write ORM.
This may be not what you're looking for, but have you tried implementing the value column in the Values table to be its own column in the Product_Params table? Then you could access each of the values by saying:
foreach($products->params as $param) {
var_dump($param->pivot->value);
}
the thing is i have 3 models wherein model1 model2's xyz(pid) is invoked which fetches the all id's contain that pid ,know model3 have (id,name) for the model2 fetched ids(fk of model3 id) ,i have looped them ,$data should store the name,id and a list of all id,name must appear in the dropdown of model1 view create
but i get the error stating
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'. The SQL statement executed was:
SELECT id,name
FROM table1
WHERE id = Array
model1
public function myabcDropDown()
{
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
foreach($sid as $val) //line 0
{
$data=model3::model()->pqr($val);
$data.=$data;
}
//line 1
$datalist=CHtml::listData($data,'id','name');
return $datalist;
}
function in model3
public function pqr($val)
{
$sql="SELECT id,name
FROM table1
WHERE id = ".$val;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryRow();
$result=array();
foreach($tts as $key=>$val1)
{
$result[]=$val1;
}
return $result;
}
function in model2
public function xyz($pid);
{
$sql="SELECT id
FROM table3
WHERE id = ".$pid;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryAll();
$result=array();
foreach($tts as $key=>$val)
{
$result[]=$val;
}
return $result;
}
Please help I am losing my mind on it
$result of xyz() is an array of rows(which in turn are arrays of fields) not of fields since queryAll was used. Use queryRow instead.
You need to learn about queryScalar() as they can help you a ;lot. now looking into your code you can do this
public function xyz($pid);
{
$sql="SELECT id
FROM table3
WHERE id = ".$pid;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$result=$command->queryColumn();
return $result;
}
Then
public function myabcDropDown()
{
$data=array();
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
if(!empty($sid))
{
foreach($sid as $value)
{
$data[]=model3::model()->pqr($value);
}
$datalist=CHtml::listData($data,'id','name');
return $datalist;
}
else
{
throw new CHttpException('I got no result');
}
}
and then finally
public function pqr($val)
{
$criteria=new CDbCriteria;
$criteria->select='id,name';
$criteria->condition='id=:id';
$criteria->params=array(':id'=>$val);
$result=Table1::model->find($criteria);
return $result;
}
Information:-
queryScalar() = You should use it if you are sure that your query is going to return single result only. It will make you free from the headache of arrays.
queryColumn() = You should use it if your are going to select a single column values in your query. It will return you one dimensional array and hence making you free from the headache of multidimensional arrays.
This wrks
public function myabcDropDown()
{
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
$datalist=CHtml::listData($sid,'id','name');
return $datalist;
}
public function xyz($pid);
{
$sql="select id ,name from table1 where id IN (SELECT id
FROM table2
WHERE pid = ".$pid.")";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryAll();
$result=array();
foreach($tts as $key=>$val)
{
$result[]=$val;
}
return $result;
}
and no need od pqr() any more