Laravel - Create or Update by defined attributes - mysql

I have this this table:
--Votes--
id: Integer
post_id: Integer
user_id: Integer
positive: Boolean
Now I would like to create a record only if it not exists. It is working until someone wants to click on dislike after he clicked on like(on the other side exactly equivalent).
For example someone likes a post a record will be created with positive=true. Now if the user clicks on the same post but this time on dislike, it will be created another record, but i want that it only updates the existing record.
Is there a simple solution?
Here is my Code to create the record:
$vote = Vote::firstOrCreate(array(
'post_id' => $request->input('post_id'),
'user_id' => Auth::user()->id,
'positive' => $request->input('positive')
));
Note: If someone knows how to do that, maybe he could show me how a deletion would be. For example someone clicks on like two times. The record should be created an deleted.

You can use updateOrCreate method:
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
have a look: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L605
EDIT:
Example
$attributes = [
'name' => 'Christian',
'email' => 'christian#example.com'
];
$values = [
'name' => 'Christian',
'email' => 'christian#example.com',
'phone' => '123456789'
];
MyModel::updateOrCreate($attributes, $values);
In the example above I will search if in my table I have an entry which match name and email, if it exists I will update the records, otherwise I will insert a new entry with the $values infos

Related

CakePHP- querying a HABTM table and then accessing data

CAKEPHP question
I am querying my HABTM table successfully and returning the id of every student with the given group_id. This is my code for this.
$students = $this->GroupsStudents->find('list', array('conditions' => array('group_id' => $id)));
It works, no problem. I need to somehow use this info (namely the student's id), which is stored in $students, to query my students table and extract student's names based on their id.
If someone could give me some insight on this, that would be greatly appreciated.
if i'm understanding you right. as you can see from this if you have the id you can easily get the students name even though i'm not sure why you would do this and not just foreach the name.
foreach ($students as $id => $name) {
echo $students[$id]; // produces name
}
In Student model define relation with GroupStudent model as shown below:
var $hasMany = array(
'GroupStudent' => array(
'className' => 'GroupStudent',
'foreignKey' => 'student_id'
)
);
Then your write your query as
$students = $this->Student->find('all',
array(
'conditions' => array('GroupStudent.group_id' => $id)
'fields'=>array('Student.name','Student.id','GroupStudent.group_id'))
);
Note: Make sure your controller has $uses=>array('Student','GroupStudent'); defined!
and your are using plural names for model GroupStudents so correct them if possible

Retrieve value from new column

I am trying to learn opencart structure, and trying to create a new column under the table product. The new column is "test"
Then I try to retrieve the data under this page index.php?route=checkout/cart (replace price with test column)
catalog\controller\checkout\cart.php
...
$this->data['products'][] = array(
'key' => $product['key'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
'price' => $product['test'], //<-- new column
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
'remove' => $this->url->link('checkout/cart', 'remove=' . $product['key'])
);
The problem is I'm not getting any output, and I'm not sure how to work with the model. Which query/function is related with this page ?
The problem is that the $products that are available at cart.php controller are retrieved from the session where they have been stored in previously set structure, so there is no test index and You should get a Notice: undefined index 'test' in .... The $products are retrieved by
foreach ($this->cart->getProducts() as $product) {
//...
}
See /system/library/cart.php and method getProducts() to understand what I am speaking about.
If You would like to use this at catalog/controller/product/category.php or catalog/controller/product/product.php controllers, the code You are trying will work.
If You replace the price within all product lists and product detail, these controllers:
product/
category.php
manufacturer_info.php
product.php
search.php
special.php
module/
bestseller.php
featured.php
latest.php
special.php
with Your value, the final price within cart would be Your test value.

Yii Query optimization MySQL

I am not very good with DB queries. And with Yii it's more complicated, since I am not very used to it.
I need to optimize a simple query
$userCalendar = UserCalendar::model()->findByAttributes(array('user_id'=>$user->id));
$unplannedEvents = CalendarEvent::model()->findAllByAttributes(array('calendar_id'=> $userCalendar->calendar_id,'planned'=>0));
CalendarEvent table, i.e the second table from which I need records does not have an user_id but a calendar_id from which I could get user_id from UserCalendar, i.e. the first table hence I created a UserCalendar object which is not a very good way as far as I understand.
Q1. What could I do to make it into one.
Q2. Yii does this all internally but I want to know what query it built to try it seperately in MySQL(phpMyAdmin), is there a way to do that?
Thanks.
Q1: You need to have the relation between UserCalendar and CalendarEvent defined in both of your active record models (in the method "relations").
Based on your comments, it seems like you have the Calendar model that has CalendarEvent models and UserCalendar models.
Lets assume your relations in Calendar are:
relations() {
return array(
'userCalendar' => array(self::HAS_MANY, 'UserCalendar', 'calendar_id'),
'calendarEvent' => array(self::HAS_MANY, 'CalendarEvent', 'calendar_id'),
}
In CalendarEvent:
relations() {
return array( 'calendar' => array(self::BELONGS_TO, 'Calendar', 'calendar_id'), );
}
And in UserCalendar:
relations() {
return array( 'calendar' => array(self::BELONGS_TO, 'Calendar', 'calendar_id'), );
}
So to make the link between UserCalendar and CalendarEvent you'll need to use Calendar
$criteria = new CDbCriteria;
$criteria->with = array(
"calendarEvent"=>array('condition'=>'planned = 0'),
"userCalendar"=>array('condition'=> 'user_id =' . $user->id),
);
$calendar = Calendar::model()->find($criteria);
and $calendar->calendarEvent will return an array of calendarEvent belonging to the user
Q2: you can enable web logging so all the db request (and others stuffs) will appear at the end of your page:
Logging in Yii (see CWebLogging)
In your application configuration put
'components'=>array(
......
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CWebLogRoute',
),
),
),
),

Codeigniter/Mysql: Column count doesn't match value count with insert_batch()?

Alright, so i have a huge list (like 500+) of entries in an array that i need to insert into a MySQL database.
I have a loop that populates an array, like this:
$sms_to_insert[] = array(
'text' => $text,
'contact_id' => $contact_id,
'pending' => $status,
'date' => $date,
'user_id' => $this->userId,
'sent' => "1"
);
And then i send it to the database using the built insert_batch() function:
public function add_sms_for_user($id, $sms) {
//$this->db->delete('sms', array("user_id" => $id)); Irrelevant
$this->db->insert_batch('sms', $sms); // <- This!
}
The error message i get is as follows:
Column count doesn't match value count at row 1.
Now, that doesn't make sense at all. The columns are the same as the keys in the array, and the values are the keys value. So, why is it not working?
Any ideas?
user_id turned out to be null in some situations, that's what caused the error.
EDIT: If you replace insert_batch() with a loop that runs insert() on the array keys you will get more clear error messages.

Trouble insert date form to mysql in drupal 7

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D