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.
Related
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.
I am curious to know what is best naming convention in terms of performance for mysql table names and column names. I am designing a new database for my project.
What I have used so far is use descriptive table/column names which sometimes seems long but I think it helps in easily understanding the use/function of a table.
For example see below DDL:
CREATE TABLE `product_configuration` (
`product_configuration_id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(20) NOT NULL,
`product_size_id` int(20) NOT NULL,
`product_color_id` int(20) NOT NULL,
`price` float NOT NULL,
`image` varchar(255) DEFAULT NULL,
`locked` tinyint(1) DEFAULT '0' COMMENT '1=locked, 0 =unlocked. if locked then this row can''t be deleted/updated',
`active` tinyint(1) DEFAULT '1' COMMENT '1=active, 0=inactive and wont display on frontend',
PRIMARY KEY (`product_configuration_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2342 DEFAULT CHARSET=latin1
And another DDL in which I use the primary key from above DDL as foreign key :
CREATE TABLE `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(255) NOT NULL,
`product_description` varchar(255) NOT NULL,
`product_image` varchar(255) NOT NULL,
`price` float NOT NULL,
`active` tinyint(1) NOT NULL COMMENT '1=active, 0=inactive',
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`product_type_id` int(11) DEFAULT NULL,
`date_modified` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1
Basically I use singular table names with table name as prefix in most of the column names inside that table and I keep the same name and datatype for primary and foreign keys so that I can easily know which foreign key relates to which primary key/tables.
But I wonder, do using long table/column names have performance impact when database size grows. Like instead of just using "id" as primary key I am using long "product_configuration_id".
Also if I name tables/columns in uppercase and lowercase mixed like
"ProductConfiguration"
for table name and
"ProductConfigurationId"
for column name will that have any performance impact or linux/windows environment compatibility issue.
Long table and column names do not have (any significant) performance impact. All tables and column references are turned into internal locators during the compilation phase of the query. So pretty much the only impact is having to query a longer query string. The parsing part of query compilation is usually ignored from a performance perspective.
The following is opinion-based. As a general rule, I follow these conventions for naming:
Table names are in the plural, because they contain multiple entities.
Each table (almost always) has an auto-incremented numeric primary key, which is the singular form of the table followed by Id.
This column is the first column defined, so I can use order by 1 desc to get the most recent rows added to the table.
The table name is not (generally) part of the column name. I always (try to) use table aliases, so including the table name would be redundant.
Foreign key references use the same column name as the primary key they are referring to, when possible, so I can use using for joins.
I admit that these are "opinion-based", so the real answer to your question is in the first paragraph.
Im trying out a sample project in CakePHP. It is taken from the cakePHP documentation. It has a total of 4 tables and two of the are listed here.
CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password CHAR(40) NOT NULL,
group_id INT(11) NOT NULL,
created DATETIME,
modified DATETIME
);
CREATE TABLE posts (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_id INT(11) NOT NULL,
title VARCHAR(255) NOT NULL,
body TEXT,
created DATETIME,
modified DATETIME
);
As you can see the id from the users table is added to the posts table as a foreign key in the form of user_id. But in the sample there are no relationships defined. I mean normally we would explicitly define user_id as a foreign key by adding the constraints (in my case using the Relation View of phpMyAdmin). But it is not done here or we are not instructed to do so. When using Cake Bake console to bake our Models do we need this foreign key constraints in place or does cakephp figure them out automatically?
Convention over configuration
Cakephp figures them out automatically for you but you have to follow the naming conventions
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
My MySQL table's primary is a composite of 2 columns: space_id (INTEGER) and day (DATE).
CREATE TABLE `ck_space_calendar_cache` (
`space_id` int(11) NOT NULL,
`day` date NOT NULL,
`available` tinyint(1) unsigned NOT NULL DEFAULT '0',
`price` decimal(12,2) DEFAULT NULL,
`offer` varchar(45) DEFAULT NULL,
`presale_date` date DEFAULT NULL,
`presale_price` decimal(12,2) DEFAULT NULL,
`value_x` int(11) DEFAULT NULL,
`value_y` int(11) DEFAULT NULL,
PRIMARY KEY (`space_id`,`day`),
KEY `space` (`space_id`),
CONSTRAINT `space` FOREIGN KEY (`space_id`) REFERENCES `ck_space` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
It works fine in raw SQL, it complains if I try to create a duplicate, but lets me create rows the the same day or the same space_id.
However, in Yii when using new Object() and save(), it complains as if "space_id" has to be unique.
I used "Giix" to generate the model if it matters.
I tried to add this code to the model, but it didn't help:
public function primaryKey(){
return array('space_id', 'day');
}
Adding this code to your ActiveRecord class is okay, but should not be necessary because Yii already has that information from your MySQL table declaration.
public function primaryKey(){
return array('space_id', 'day');
}
When Yii complains about "space_id" to be unique, giix might have added a validation rule to rules() in your ActiveRecord class. These rules are checked before an ActiveRecord is saved and it will only save if all rules are okay. Read the Data Validation section of Definitive Guide for more information.
From what I understand since Yii 1.1 composite primary keys are not longer supported with Gii, which is frustrating many developers. There are other poorly documented alterations needed in your code aside from the returning an array as a primary key.
The best explanation I found was in this discussion in the Yii forum.