Laravel eloquent where clause issue - php

I have the following structure of the table:
`id` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`order` int(11) NOT NULL,
`category` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
I have five confirm records in table where i am querying table like this :
$recommended = App\Recommend::where('category', '=', 'editorpicks');
But the result comes empty, Let me paste the column name and value against it straight from DB.
column name : category
value : editorpicks.
Why its not working.
I have tried it in tinker also.

App\Recommend::where('category', 'editorpicks')->get();
Note, you don't need to use "=" in where, if no conditional is provided, the where clause will default to equals. get() grabs the collection. You could also do first() to grab first single record, last(), find($id), etc.
It's also good practice to namespace the model as well. So add use App\Recommend to top of controller (I'll assume this already makes sense) and then just use $recommended = Recommend::where(.... Keep things clean.

Related

Laravel 5 belongsTo(classname::class) doesn't works

Due to a Model Name change, my class Student doesn't works properly now.
With a database called assos:
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8mb4_unicode_ci NOT NULL,
`student_id` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
linked with a model Asso,
The query App\Asso::first()->belongsTo(Student::class) returns null
When the query App\Asso::first()->belongsTo('App\Student','student_id') returns the associated student.
I don't understand why belongsTo(Student::class) doesn't work properly. Can you help me to figure it out?
Thanks a lot
From Eloquent: Relationships One To One :
Eloquent determines the default foreign key name by examining the name
of the relationship method and suffixing the method name with _id.
Since you seem to be defining a relationship inline, the method name likely isn't student so it's not looking for student_id, it's looking for mehtodname_id.
In your second example you're telling it which field to look for the relation in, so it's looking at the right one.
Unrelated to the question specifically, but you're really misusing relationship methods. These should be defined in the model.

MySQL INSERT ... OR UPDATE Explanation

I know there are many examples of how to use this as well as links to the MySQL documentation. Unfortunately, I am still a in need of clarification on how it actually works.
For instance, The following table structure (SQL code) is one example of what I need to use the INSERT ... OR UPDATE:
CREATE TABLE IF NOT EXISTS `occt_category` (
`category_id` int(11) NOT NULL,
`image` varchar(255) DEFAULT NULL,
`parent_id` int(11) NOT NULL DEFAULT '0',
`top` tinyint(1) NOT NULL,
`column` int(3) NOT NULL,
`sort_order` int(3) NOT NULL DEFAULT '0',
`status` tinyint(1) NOT NULL,
`date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
ALTER TABLE `occt_category` ADD PRIMARY KEY (`category_id`);
ALTER TABLE `occt_category` MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
What I am attempting to insert into this mess are new categories from an API source so there are definitely duplicates.
What I am getting from the API is the following:
[
{
"categoryID": 81,
"name": "3/4 Sleeve",
"url": "3-4sleeve",
"image": "Images/Categories/81_fm.jpg"
}
]
So given the above information; Do I need to change my table structure to check for duplicates coming in from the API?
In MSSQL I would just simply do an IF EXISTS .... statement to check for duplicates. Unfortunately, this is MySQL :(.
If you intend to make use of the INSERT ... ON DUPLICATE KEY UPDATE MySQL Syntax (which is what I understand from your question, as INSERT ... OR UPDATE is not a real MySQL command), then your current table structure is fine and you will NOT have to check for duplicate records.
The way this works is that before writing any new records into your table, the MySQL DB will first check to see if there are any records that have a value in a PRIMARY or UNIQUE key-field (in your case category_id) that is the same value for the corresponding field in the incoming record, if it finds one, it will simply update that record as opposed to writing a new one.
You can read more about this syntax here.

How to speed up the SELECT query of the following table?

I have a mysql table whose create code is as follows :
CREATE TABLE image_ref (
region VARCHAR(50) NULL DEFAULT NULL,
district VARCHAR(50) NULL DEFAULT NULL,
district_name VARCHAR(100) NULL DEFAULT NULL,
lot_no VARCHAR(10) NULL DEFAULT NULL,
sp_no VARCHAR(10) NULL DEFAULT NULL,
name VARCHAR(200) NULL DEFAULT NULL,
form_no VARCHAR(50) NOT NULL DEFAULT '',
imagename VARCHAR(50) NULL DEFAULT NULL,
updated_by VARCHAR(50) NULL DEFAULT NULL,
update_log DATETIME NULL DEFAULT NULL,
ip VARCHAR(50) NULL DEFAULT NULL,
imgfetchstat VARCHAR(1) NULL DEFAULT NULL,
PRIMARY KEY (form_no)
)
COLLATE='latin1_swedish_ci'
ENGINE=MyISAM;
This table contains approximately 7,00,000 number of rows. I have an application developed using PHP. Somewhere I need to run the following query :
SELECT
min(imagename) imagename
FROM
image_ref
WHERE
district_name = '$sess_district'
AND
lot_no = '$sess_lotno'
AND
imgfetchstat = '0';
which is taking on average 1.560 sec. The form_no field only has unique values. After some job is done with the result set fetched, the imgfetchstat is required to be updated with a value 1. Now my requirement is that, whether I should use InnoDB or MyISAM? Also, the application is accessed by around 50 numbers of users in LAN. Is there any way out to run the above query little bit faster? because the imagename fetched is being used to load an image of resolution 500 x 498 into the browser and the it is taking enough time to load the image. Thanks in advance.
You can add indexes to your table (be aware that this will make the storage larger - but given your query, you should be able to use the following:
ALTER TABLE `table` ADD INDEX `product_id` (`product_id`)
For more information see http://dev.mysql.com/doc/refman/5.0/en/create-index.html
You can add an index on a single column (which makes things nice for the DB, even it it uses a few of them on a query) but if you have a secific query that needs to REALLY run fast, you can add a multi-column index which is specific to your query:
ALTER TABLE image_ref ADD INDEX `someName`
(`district_name`, `lot_no`, `imgfetchstat`)

Insert/Update Issue (Same record repeated, no more can be entered)

I'm a bit baffled here, and my code is a bit too lengthy to post it all, but I'll provide a logical list of the operations in hand and can provide the code where needed if it helps, but the problem is weird and I don't think it's to do with the code. It's a standard upload form for an article website.
On first load, assign random article_ID
Check if article_ID already exists. If it does, repeat step 1
On save (submit), insert article_ID (the only required value [for testing purposes], the rest can be NULL)
Any of other fields entered are checked for content, and if there is some entered update where article_ID = $article_ID.
It's quite a simple system, make a template of an article with an article_ID where all the other fields can be NULL. The user adds the content piece by piece saving along the way until all the fields are entered so the article can be published.
However, the first time I got it working, an article_ID was assigned and the template inserted. Now I can't insert any other records, and more oddly still if I delete that record and then create a new form instance with a new article_ID and INSERT, it just keeps adding the same record with the old article_ID, even though the form has no session variables with that old article_ID still stored.
Has anyone had something similar?
Database Structure
`article_ID` int(10) NOT NULL,
`author_ID` int(5) NOT NULL,
`article_title` varchar(50) NOT NULL,
`article_subtitleshort` varchar(120) default NULL,
`article_subtitlelong` varchar(180) default NULL,
`article_category` varchar(20) NOT NULL,
`article_featureimage` varchar(15) default NULL,
`article_icon` varchar(15) default NULL,
`article_publishdate` varchar(12) default NULL,
`article_lastsavedate` varchar(12) NOT NULL,
`article_status` varchar(11) NOT NULL default 'unpublished',
`article_firstimage` varchar(15) default NULL,
`article_intro` varchar(600) default NULL,
`article_firsttext` blob,
`article_secondimage` varchar(15) default NULL,
`article_secondtext` blob,
`article_thirdimage` varchar(15) default NULL,
`article_youtube` varchar(50) default NULL,
`article_gallery` varchar(10) default NULL,
PRIMARY KEY (`article_ID`)
Relevant Code http://snippi.com/s/57j8i7e
I suspect the INSERT is failing because you are inserting a INTs as VARCHARs. Change it as follow - Remove the single quotes passing it through as VARCHAR incorrectly.
Also verify that your SELECT statement will return record as you are using the same logic when you pass the $article_ID i.e. remove the single quotes. Also not necessary to check for the random value.
Please make use of AUTO_INCREMENT for article_ID instead of randomly generating the value.
mysql_query("INSERT INTO articles (author_ID) VALUES ($author_ID)");
article_ID will be populated with a unique value

Comparison time for 2 large MySQL database table

I have imported 2 .csv file that I wanted to compare into MySQL table. now i want to compare both of them using join.
However, whenever I include both table in my queries, i get no response from phpMyAdmin ( sometimes it shows 'max execution time exceeded).
The record size in both db tables is 73k max. I dont think thats huge on data. Even a simple query like
SELECT *
FROM abc456, xyz456
seems to hang. I did an explain and I got this below. I dont know what to take from this.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE abc456 ALL NULL NULL NULL NULL 73017
1 SIMPLE xyz456 ALL NULL NULL NULL NULL 73403 Using join buffer
can someone please help?
UPDATE: added the structure of the table with composite keys. There are around 100000+ records that would be inserted in this table.
CREATE TABLE IF NOT EXISTS `abc456` (
`Col1` varchar(4) DEFAULT NULL,
`Col2` varchar(12) DEFAULT NULL,
`Col3` varchar(9) DEFAULT NULL,
`Col4` varchar(3) DEFAULT NULL,
`Col5` varchar(3) DEFAULT NULL,
`Col6` varchar(40) DEFAULT NULL,
`Col7` varchar(200) DEFAULT NULL,
`Col8` varchar(40) DEFAULT NULL,
`Col9` varchar(40) DEFAULT NULL,
`Col10` varchar(40) DEFAULT NULL,
`Col11` varchar(40) DEFAULT NULL,
`Col12` varchar(40) DEFAULT NULL,
`Col13` varchar(40) DEFAULT NULL,
`Col14` varchar(20) DEFAULT NULL,
KEY `Col1` (`Col1`,`Col2`,`Col3`,`Col4`,`Col5`,`Col6`,`Col7`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
It looks like you are doing a pure catesian join in your query.
Shouldn't you be joining the tables on certain fields? If you do that and the query still takes a long time to execute, you should put appropriate indexes to speed up the query.
The reason that it is taking so long is that it is trying to join every single row of the first table to every single row of the second table.
You need a join condition, some way of identifying which rows should be matched up:
SELECT * FROM abc456, xyz456 WHERE abc456.id = xyz456.id
Add indexes on joining columns. That should help with performance.
Use MySQL Workbench or MySQL Client (console) for long queries. phpmyadmin is not designed to display queries that return 100k rows :)
If you REALLY have to use phpmyadmin and you need to run long queries you can use Firefox extension that prevents phpmyadmin timeout: phpMyAdmin Timeout Preventer (direct link!)
There is a direct link, because i couldnt find english description.

Categories