I am trying to validate the input of a email address that exists but only when the company_id is the same as the company_id which is passed in with the request.
I am getting this error...
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause' (SQL: select count(*) as aggregate from company_users where email_address = myemail.com and 1 <> company_id)
I have read online and the way to do it is to associate the table and the column inside of the validation which is what I am doing.
This is my current code...
required|email|unique:company_users,email_address,company_id,' . $request->company_id
Here is a rough idea with this you can achieve what you
You can use Rule class to customize the validation rule for you.
'email' => ['required', 'string', 'email', 'max:191',Rule::unique('users')->where(function ($query) use ($request) {
return $query->where('company_id', $request->company_id);
})],
Hope this helps
This should answer your question.
'required|email|unique:company_users,email_address,NULL,id,company_id,' . $request->company_id
This means, the email must be unique while ignoring a row with an id of NULL and where its company_id is the same as $request->company_id.
The except parameter ignores rows to compare against the validation. E.g., an email address of abc#gmail.com has already been taken by user 1 but you did this:
'unique:company_users,email_address,1'
It will ignore user with id of 1. So inputting the same email will still pass since the existing user with the same email has been ignored.
Which is not the same in your case, because you just dont want to ignore a special row, but you want to ignore a row based on a condition. So that is how this answer helps you, by adding more field validations after the ignore parameter.
You might want to take a look at this: laravel 4: validation unique (database) multiple where clauses
It has to be like:
required|email|unique:company_users,email_address,' . $request->company_id
The format is:
unique:table,column,'id to exclude'
Or if you want to validate based on a column you can do a separate query:
$exists = Model::where('company_id','!=',$request->company_id)->where('email',$request->email)->count()
if($exists) {
// return an error or a validation error
}
Make $request->company_id a string by adding ' single quotes around your variable. Otherwise MySQL will think is a column in your table.
required|email|unique:company_users,email_address,company_id,"'" . (int) $request->company_id . "'"
Related
I'm working on a MySQL Way of printing an "affiliate tree" and got the thing working with Common Table Expression. I'm using the following code right now:
WITH RECURSIVE recUsers AS
(
SELECT ID, username, sponsorID, 1 AS depth, username AS path
FROM users
WHERE id = 1
UNION ALL
SELECT c.ID, c.username, c.sponsorID, sc.depth + 1, CONCAT(sc.path, ' > ', c.username)
FROM recUsers AS sc
JOIN users AS c ON sc.ID = c.sponsorID
)
SELECT * FROM recUsers;
This selects the tree underneath the user with the id 1.
Now what I'd need to get is a way to pass that id as a parameter, so I don't need to define everything from the beginning every time I want to get the result.. So my idea is to put everything in a stored prodecure and pass the id in as a parameter.. However, so far I didn't get it working and always getting various errors that are very self speaking...
Basically what I've tried was
DELIMITER //
CREATE PROCEDURE getAffiliateTree(IN userid INT())
BEGIN
---my code here, the userid 1 replaced with userid
END//
DELIMITER;
However, this doesn't seem to work.. How can I get this done?
Two things I would suggest:
Use INT, not INT(). The optional length argument to integer types is deprecated in MySQL 8.0 (which I know you're using, because you're using CTE syntax). Even if you did use the length argument, using an empty argument is not legal syntax.
Make sure that the userid input parameter name is distinct from all of the columns in the tables you reference. That is, if the table has a column named userid (any capitalization), then change the name of your input parameter. Otherwise you may make ambiguous expressions like:
... WHERE userid = userid
Even though you intend one of these to be the column and the other to be the parameter, the SQL parser has no way of knowing that. It ends up treating both as the column name, so it's trivially true on all rows of the table.
Actually, a third thing I would suggest: when you ask questions, "it doesn't seem to work" isn't clear enough. Did it produce an error? If so, what was the full error message? Did it produce no error, but didn't give you the result you wanted? If so, show a mocked-up example of what you expected, and what the query produced that didn't match. It helps to be as clear as you can when you post questions, so readers don't have to guess what trouble you need help with.
I am looking for the active record version of the following sql code:
select *
from users
where (details->'email') is not null
Let's say that my User model has a json field called, details, and some records will have an email key-value and some will not. I'm trying to query the user records that have an email, key-value. I tried using the following, User.where("details->'email' is not null"), but my terminal prints out this:
PG::UndefinedFunction: ERROR: operator does not exist: json -> boolean
I found this SO post, which attempts to do the opposite query, but the idea is the same. If someone can show me the Active Record version of querying where a json key is or is not present, I'd greatly appreciate it.
This worked for getting users with an email key:
User.where("(details->'email') is not null")
This worked for getting users without an email key:
User.where("(details->'email') is null")
I'm retrieving my records using CActiveRecord with a with() statement:
Probes::model()->with(array
(
'user',
'results',
'results.answer',
'survey',
'survey.questions'
))->findByPk($id)
I wanted to use GROUP BY on question_id field of survey.questions relation, so I changed above to:
'survey.questions'=>array('group'=>'survey.questions.question_id'),
This caused a SQL exception 1054 Unknown column. However, by analyzing attached SQL code:
`questions`.`question_id` AS `t6_c2`
I managed to find out, that I have to use t6_c2 alias (auto-generated by Yii?). So, another change to:
'survey.questions'=>array('group'=>'t6_c2'),
and the problem is solved.
But, then again, alias t6_c2 seems quite... "unstable" (auto-generated?) for me. Can I force Yii to in this part of generated SQL some other alias, provided by me? Or how certain can I be, that this part of SQL code won't change upon next (some later) generation? Or -- is there any other way to achieve, what I want to achieve?
you can assign alias to your relation
,
'survey.questions'=>array(
'alias' => 'surq'
'group'=>'surq.question_id',
),
read this and this for more info
You can set specific and unique alias for each relation table in a relations method in your model. For example,"user"=>array(self::HAS_MANY, "User", "user_id", "alias"=>"your_alias_for_this_relation")
Try this (i'm asumming 'survey.questions' is a field of the table probe)
Prove::model()->findByPk($id)->survey.questions, CHtml::listData(Prove::model()->findAll(array("order"=>"survey.questions")),
I want to produce sql like:
select id, "file_name.png" from prefix_table;
In CI, by using active records, I code that with:
$this->db->select('id, "file_name.png"', FALSE)->from('prefix_table');
but what I got is:
select id, prefix_"file_name.png" from prefix_table;
Is there any way to use the table prefix optional? Or may be, how do I do not use the prefix when selecting using active records?
This is a limitation/bug in CodeIgniter right now -- you won't be able to use a string like that without the prefix butting in. I'd suggest writing the query manually. I've opened an issue on Github for it.
Also, you should use an AS column definition when selecting a string like that, otherwise the string name will also be the column name, and you'll end up with something like:
array(
'id' => 2,
'file_name.png' => 'file_name.png'
)
I keep getting MySQL error #1054, when trying to perform this update query:
UPDATE MASTER_USER_PROFILE, TRAN_USER_BRANCH
SET MASTER_USER_PROFILE.fellow=`y`
WHERE MASTER_USER_PROFILE.USER_ID = TRAN_USER_BRANCH.USER_ID
AND TRAN_USER_BRANCH.BRANCH_ID = 17
It's probably some syntax error, but I've tried using an inner join instead and other alterations, but I keep getting the same message:
Unknown column 'y' in 'field list'
Try using different quotes for "y" as the identifier quote character is the backtick (`). Otherwise MySQL "thinks" that you point to a column named "y".
See also MySQL 8 Documentation
Please use double-/single quotes for values, strings, etc.
Use backticks for column-names only.
Enclose any string to be passed to the MySQL server inside single quotes, e.g.:
$name = "my name"
$query = " INSERT INTO mytable VALUES ( 1 , '$name') "
Note that although the query is enclosed between double quotes, you must enclose any string in single quotes.
You might check your choice of quotes (use double-/ single quotes for values, strings, etc and backticks for column-names).
Since you only want to update the table master_user_profile I'd recommend a nested query:
UPDATE
master_user_profile
SET
master_user_profile.fellow = 'y'
WHERE
master_user_profile.user_id IN (
SELECT tran_user_branch.user_id
FROM tran_user_branch WHERE tran_user_branch.branch_id = 17);
Just sharing my experience on this. I was having this same issue. The insert or update statement is correct. And I also checked the encoding. The column does exist.
Then! I found out that I was referencing the column in my Trigger.
You should also check your trigger see if any script is referencing the column you are having the problem with.
In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.
While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value"); statement.
Turns out I misspelled the columnName.
If it is hibernate and JPA. check your referred table name and columns might be a mismatch
Just sharing my experience on this. I was having this same issue. My query was like:
select table1.column2 from table1
However, table1 did not have column2 column.
In my case, the Hibernate was looking for columns in a snake case, like create_date, while the columns in the DB were in the camel case, e.g., createDate.
Adding
spring:
jpa:
hibernate:
naming: # must tell spring/jpa/hibernate to use the column names as specified, not snake case
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
to the application.ymlhelped fix the problem.
In my case, I used a custom table alias for the FROM table, but I used the default table alias (MyTable) in the field list instead of the custom table alias (t1). For example, I needed to change this...
mysql> SELECT MyTable.`id` FROM `MyTable` t1;
...to this...
mysql> SELECT t1.`id` FROM `MyTable` t1;
In my case I had misspelled the column name in the table's trigger. Took me a while to connect the error message with the cause of it.
I too got the same error, problem in my case is I included the column name in GROUP BY clause and it caused this error. So removed the column from GROUP BY clause and it worked!!!
I got this error when using GroupBy via LINQ on a MySQL database. The problem was that the anonymous object property that was being used by GroupBy did not match the database column name. Fixed by renaming anonymous property name to match the column name.
.Select(f => new
{
ThisPropertyNameNeedsToMatchYourColumnName = f.SomeName
})
.GroupBy(t => t.ThisPropertyNameNeedsToMatchYourColumnName);
A query like this will also cause the error:
SELECT table1.id FROM table2
Where the table is specified in column select and not included in the from clause.