i want to insert a new record if doesn't exist and update it if exists, i came across a method updateOrCreate, but im having hard time implementing it
$list = mList::updateOrCreate(
[
['user_id' => 162, 'movie_id' => 862]
],
[ 'tag' => 'watched'] //this data should be updated if the above got match
);
but im getting the following query exception
SQLSTATE[42S22]: Column not found: 1054 Unknown column '162' in 'where clause' (SQL: select * from lists where (162 = 862) limit 1)
it should look for a column called user_id not 162
ps: im doing this with two conditions where(user_id = 162 and movie_id =862)
but when i do it with a single condition it works surprisingly.
if there is any other eloquent method can do the same please refer to me ..
Try using [ ] insead of [ [ ] ], like:
$list = mList::updateOrCreate([
'user_id' => 162,
'movie_id' => 862
], [
'tag' => 'watched'
]);
Related
I have this table that contains my site settings:
I would want to update all records at once with data that comes from a form.
The data looks like this:
$data = [
"brand" => "bbb"
"mail" => "kontakt#aaa.pl"
"phone" => "111"
"site-name" => "test"
];
Now I would like to update that with key of the associative array and with it value.
I tried:
DB::table('settings')->update($data);
But there is an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'brand' in 'field list' (SQL: update `settings` set `brand` = bbb, `mail` = kontakt#aaa.pl, `phone` = 111, `site-name` = test)
Obviously it thinks that brand is a column name.
So I transformed the $data to this array:
$data = [
0 => [
"name" => "brand"
"value" => "bbb"
]
1 => [
"name" => "mail"
"value" => "kontakt#aaa.pl"
]
2 => [
"name" => "phone"
"value" => "111"
]
3 => [
"name" => "site-name"
"value" => "test"
]
];
and now the error is:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update `settings` set `0` = {"name":"brand","value":"bbb"}, `1` = {"name":"mail","value":"kontakt#aaa.pl"}, `2` = {"name":"phone","value":"111"}, `3` = {"name":"site-name","value":"test"})
So now it thinks that index of each row in array is column name and at this place i have no idea how to do this...
Can anyone help me please?
I came to this solution although i think it looks ugly and there should be a better way to do this, if no better answers will be given i will mark my answer as correct
$data = [
"brand" => "bbb"
"mail" => "kontakt#aaa.pl"
"phone" => "111"
"site-name" => "test"
];
foreach($data as $key=>$d) {
DB::table('settings')->where('name','=',$key)->update(['value' => $d]);
}
Your table looks something like you can only take a set of data and update it with time. Why because there are no foreign key relations.
if that is the case then why not have brand_name, mail, phone and site_name for settings columns,
Your migrations
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->string('brand_name');
$table->string('mail');
$table->string('phone');
$table->string('site_name');
$table->timestamps();
});
}
In your model?
protected $fillable = ['brand_name', 'mail', 'phone', 'site_name'];
or
protected $guarded = [];
In your controller
public function method(Request $request)
{
// You can also abstract this in to a custom request class
$request->validate([
'brand_name' => 'required',
'mail' => 'required',
'phone' => 'required',
'site_name' => 'required',
]);
// Add data if record doesn't exist, update when it does
// To use the validated method on request all needed fields must be required
Settings::updateOrCreate($request->validated())
}
Should in case I was wrong you can still check out Laravel Mass Update
https://laravel.com/docs/8.x/eloquent#mass-updates
Laravel Upserts
https://laravel.com/docs/8.x/eloquent#upserts
You can use upsert to update multiple records
First transform data to add column name using collection
$data=collect($data)->transform(function ($value,$name){
return ["name"=>$name,"value"=>$value];
})->values()->toArray();
and here i used model
Setting::upsert($data,["name"],["value"]);
To understand Upserts
Upsert perform multiple "upserts" in a single query
first argument consists of the values to insert or update
second argument lists the column(s) that uniquely identify records within the associated table.
third and final argument is an array of the columns that should be updated if a matching record already exists in the database.
Also important point
All databases systems except SQL Server require the columns in the
second argument provided to the upsert method to have a "primary" or
"unique" index.
It means in your mysql table settings column name to be unique index or else it will insert as new row
Ref:https://laravel.com/docs/8.x/eloquent#upserts
I have this model:
Proforma
->hasMany('ItemProformas', ['foreignKey' => 'proforma_id']);
->belongsTo('Customers', ['foreignKey' => 'customer_id']);
->belongsTo('ProformaStates', ['foreignKey' => 'proforma_state_id']);
->hasMany('Invoices', ['foreignKey' => 'proforma_id']);
ItemProformas
->belongsTo('Proformas', ['foreignKey' => 'proforma_id', 'joinType' => 'INNER']);
->belongsTo('ItemDeliveryNotes', ['foreignKey' => 'item_delivery_note_id']);
ItemDeliveryNotes
->belongsTo('DeliveryNotes', ['foreignKey' => 'delivery_note_id', 'joinType' => 'INNER']);
->belongsTo('ItemOrders', ['foreignKey' => 'item_order_id']);
->belongsTo('ItemOrdersTypes', ['foreignKey' => 'item_orders_type_id']);
->belongsTo('Products', ['foreignKey' => 'product_id']);
Each ItemProforma may have one ItemDeliveryNotes, otherwise the foreign key will be null. Here my paginate call:
$this->paginate = [
'contain' => [
'Customers',
'ProformaStates',
'ItemProformas' => ['ItemDeliveryNotes' => ['DeliveryNotes']]
]
];
With this model, I get all the itemProforma that have item_delivery_note_id set. Instead I'm interesed to get them all, even if item_delivery_note_id is null.
I'm not sure if belongsTo is correct here (I mean in ItemProformas definition). But hasOne implies it has one associated row, not may have one.
What is the correct syntax to retrieve all itemProformas even if they don't have any ItemDeliveryNote associated? But if they have, I need to retrieve the ItemDeliveryNote object as well.
The association type depends on your schema. If the foreign key is in the source table, then it's belongsTo, if the foreign key is in the target table, then it's hasOne.
Whether a related record must exist primarily depends on the schema too, not on the type of association. If the foreign key is nullable, then the related record is optional. If and how you implement enforcing that constraint on application level is a different story.
That being said, ItemDeliveryNotes and DeliveryNotes are both belongsTo that will use joins by default, so both associations will be joined into the same query, and since you've configured the DeliveryNotes association to use an INNER join, it will exclude rows where no DeliveryNotes exist, which of course is also the case when no ItemDeliveryNotes exist.
Assuming your schema is modeled correctly/properly, you could for example change your association config to use a LEFT join by default in case applicable, or you could change the configuration for the containment on a per query basis (being it manually, or by using a custom finder):
$this->paginate = [
'contain' => [
'Customers',
'ProformaStates',
'ItemProformas' => [
'ItemDeliveryNotes' => [
'DeliveryNotes' => [
'joinType' => \Cake\Database\Query::JOIN_TYPE_LEFT,
],
],
],
],
];
Changing the fetching strategy for ItemDeliveryNotes could work too (though it might be quite taxing depending on the amount of records), ie using the select strategy instead of the join strategy, then the associated ItemDeliveryNotes records are being retrieved in a separate query, and thus won't affect retrieval of ItemProformas:
$this->paginate = [
'contain' => [
'Customers',
'ProformaStates',
'ItemProformas' => [
'ItemDeliveryNotes' => [
'strategy' => \Cake\ORM\Association::STRATEGY_SELECT,
'DeliveryNotes',
],
],
],
];
Hello everyone am newly in laravel and i am trying to get data.using state ID please explain me with all Model with relationship each-other with example i have tables like this
1- states table
1- id
2-name
2- cities table
1- id
2-name
3- state_cities pivot table
1-id
2-sate_id
3-city_id
4- locations table
1-id
2-name
5- city_locations pivot table
1-id
2-city_id
3-location_id
6- pincodes table
1-id
2-pincode
7- location_pincodes table
1-id
2-location_id
3-pinecode_id
And this is my Controller
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
and that is error which is am geting
"message": "Trying to get property of non-object",
"exception": "ErrorException",
"file": "D:\\xampp\\htdocs\\samudaay-backend\\app\\Http\\Controllers\\API\\PincodeController.php",
"line": 32,
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
// Location is the 'key' of the object in the collection. So it probably will be something like '0' or '1'.
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
//What you actually do here is: 0->locationName->map(...). This will result in your error
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
$location in the first map function is the key of the object it is iterating at the moment. (see: https://laravel.com/docs/5.6/collections#method-map)
So on line 32 you are trying to call a property on the key variable (which will probably be '0' or '1' or something.) As that is not an object, it will result in the error you get.
Also, trying to map the locationName property is not going to work as expected. locationName is a property and not an eloquent collection.
You should probably try it like this:
'location' => [
'location_id' => $location->location_id,
'location_name' => $location->name
];
})
I am new to laravel and want to add validation of unique url with where clause in update case. I have tried both codes but none seems to be working.
'page_url' => [ 'required',
Rule::unique('pages')->ignore($id_page,'id_page')
],
'page_url' => 'required|unique:pages,page_url,null,null,id_page,!'.$id_page,
Error
Column not found: 1054 Unknown column 'pages.id' in 'where clause'
Thanks in advance.
It works by adding this in model:
protected $primaryKey = 'id_page';
I am storing my articles view count in MongoDB like this
$mongoCollection = $this->mongoClient->db->collectionName;
$mongoCollection->findAndModify(
[
'id' => (int)$article_id
],
[
'$inc' => [
'count' => 1
]
],
null,
[
'upsert' => true
]
);
Now i need to add an index, so i am just adding
$mongoCollection->createIndex(['id' => 1]);
right after
$mongoCollection = $this->mongoClient->db->collectionName;
but this gives me
Index with name: id_1 already exists with different options
But why? By http://php.net/manual/en/mongocollection.createindex.php and https://docs.mongodb.org/v3.0/tutorial/create-an-index/ it must work?
What am i doing wrong? And is it right to add
['unique' => true, 'dropDups' => 1]
in this case?
Well the error message says it all: Index with name: id_1 already exists with different options
You all ready have an index with that name. You only need to create an index once - not every time you connect to the database.