Select condition where related rows doesn't exist [duplicate] - mysql

This question already has an answer here:
How can i use Yii.ActiveRecord to find unrelated records?
(1 answer)
Closed 10 years ago.
I am using Yii in the development of an internal administration system for a company. I have created a model Jobs, and this model have relations to the model Quotes of type HAS_MANY. The relation name is quotes. Now i need to select all rows (the model Jobs uses the MySQL table jobs as it's source) where each job has exactly 0 quotes associated with it. I thought that i would add this as a scope in the model. How do i accomplish this?

in model add:
public function scopes() {
return array(
'withoutQuotes'=>array(
'with'=>'quotes',
'condition'=>'quotes.id is null',
),
);
}
and then use
$model->withoutQuotes()->search() //etc

Related

How to add two foreign keys in message table of same(user) table as foreign keys? [duplicate]

This question already has an answer here:
fields.E304 Reverse accessor clashes in Django
(1 answer)
Closed 10 months ago.
I am trying to design a chatting app using Django rest at the backend
My Model
class MessageModel(models.Model):
message = models.CharField(max_length=200)
msg_from = models.ForeignKey(UserModel,on_delete=models.CASCADE)
msg_to = models.ForeignKey(UserModel,on_delete=models.CASCADE)
but it gives the following error
SystemCheckError: System check identified some issues:
ERRORS:
message_api.MessageModel.msg_from: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_from' clashes with reverse accessor for 'message_api.MessageModel.msg_to'.
HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_from' or 'message_api.MessageModel.msg_to'.
message_api.MessageModel.msg_to: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_to' clashes with reverse accessor for 'message_api.MessageModel.msg_from'.
HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_to' or 'message_api.MessageModel.msg_from'.
How can I design a database table for chatting?
I am using MySQL database.
class MessageModel(models.Model):
message = models.CharField(max_length=200)
msg_from = models.ForeignKey(UserModel,on_delete=models.CASCADE, related_name="msg_sender")
msg_to = models.ForeignKey(UserModel,on_delete=models.CASCADE,related_name="msg_reciever")
Good advice from Willem also don't use the Model suffix, instead name your models "Message" and "User"

Issues when getting ID from DB [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
I hope you all have a good day.
Actually I'm deploying a query to get a complete array of data. But the fact is that I need an Id, first of all, I guess, I must get the last Id first, then I can apply a mathematic operation to get its value + 1. The fact is that I've been trying different sentences and queries with no result.
This is my code:
function obtener_Id(){
global $mysqli;
$resultado_oId = $mysqli ->query("SELECT TOP 1 'id' FROM 'pacient' ORDER BY RowID DESC ")
$id_sacada = mysqli_fetch_assoc($resultado_oId);
$id_enLaMano = $id_sacada['id'];
return $id_enLaMano;
//$id_dinamica = $id_enLaMano + 1;
//return $id_dinamica;
}
As you can see guys, I've commented on the last two lines, cause I´m looking to get at least a value (The result from a query) But Idk if that is correct. Looking on the Internet I've seen relative posts which are solved just to apply the query that we can view under global declarations...
I've tried that on phpMyAdmin with no results and a bunch of errors...
You guys know the correct way to get the max value in the Id column? Or even if I'm doing badly correct me.
A lot of hugs and Luck!
Mizar ^^
I would suggest putting the serial number in a table. Read the serial no before insert, (lock the table, if required) insert the data, then increase the serial no by 1 and update the serial no table with increased value.

MySQL - How extract value from stdClass when addressing by index or conversion to array fails [duplicate]

This question already has an answer here:
Execute SQL functions with Laravel 5
(1 answer)
Closed 2 years ago.
Currently making a study project, implementing a library in Laravel. I have written a procedure to calculate the amount of time a certain book was taken yearly:
$queryString = "SELECT ReadBookTakenPeriodPerYear({$id});";
$result = DB::select($queryString);
As a result, I am getting:
array (
0 =>
array (
0 =>
stdClass::__set_state(array(
'ReadBookTakenPeriodPerYear(33)' => 1.91781,
)),
),
)
How can I get that 1.91781? Why can't I access the array by index, or convert the sdt-class to array? Researched for a solution on inet, on SO, still can't cope with it.
array (
0 =>
array (
0 =>
stdClass::__set_state(array(
'ReadBookTakenPeriodPerYear(33)' => 1.91781,
)),
),
)
You have a few layers of unneeded nesting in this return data. You have a php standard object which is the first and only element in an array. That array is the first and only element in a parent array. As it stands, you should be able to get the value like this:
$result[0][0]->ReadBookTakenPeriodPerYear(33);
You can simplify the returned data to make this slightly more straightforward by adding a ->first().
$result = DB::select($queryString)->first();
Adding ->first() here should eliminate one level of array. You are telling query builder to give you the first matching result rather than a collection of all of them. Now you should be able to do:
$result[0]->ReadBookTakenPeriodPerYear(33);
Combine this with use of the laravel helper Arr::get() to avoid an exception if no data is found in the database. https://laravel.com/docs/master/helpers#method-array-get
Arr::get($result, 0)->ReadBookTakenPeriodPerYear(33);
And,finally, the Laravel helper method optional() to make sure $results[0] returned an object before looking for the attribute on it to avoid an exception at that level. https://laravel.com/docs/master/helpers#method-optional
optional(Arr::get($result, 0))->ReadBookTakenPeriodPerYear(33);
That should get you the data, and also be able to handle cases where data wasn't found in the database without crashing.
I hope it helps!

SET mysql variable with list of mails [duplicate]

This question already has answers here:
How to pass a variable to a IN clause?
(4 answers)
Closed 5 years ago.
I need to define a list of variables to use in multiple MySQL queries.
The variable will be a list of mails. I have tried to define it in different ways but it always gives me error in the construction.
SET #listamails='mail1#gmail.com,mail2#gmail.com';
Select * from user WHERE mail IN (#listamails);
Any ideas?
Thank you
You cannot pass in a list to IN using a single variable. The simplest solution in MySQL is find_in_set():
Select u.*
from user u
where find_in_set(mail, #listamails) > 0;
However, this cannot take advantage of an index. For that, you might want to use dynamic SQL.
Try this
SET #listamails='mail1#gmail.com','mail2#gmail.com';
Select * from user WHERE mail IN (#listamails);

Using variables for relationsships while importing from csv [duplicate]

This question already has answers here:
Neo4j - changing relationship type not working in web interface data browser
(2 answers)
Closed 6 years ago.
I want to migrate a project from a SQL graph database 'emulation' to neo4j, and now I'm stuck. I have a table with 100000+ rows of the form source_id, relationship_type, target_id.
Here's the import statement:
LOAD CSV WITH HEADERS FROM
'file:///usr/local/n4jinput/special_semrelations.csv' AS line
WITH line
MATCH (s:SemObject {sem_id: TOINT(line.ool_source_id)})
MATCH (t:SemObject {sem_id: TOINT(line.ool_target_id)})
CREATE (s)-[line.rlt_relation]->(t)
The problem is in the create statement. What is the correct syntax to retrieve [:WHATEVER_IS_IN_THE_CSV]? Since I have a few dozen relationship types, I need to use some kind of variable here... If this is not possible in CYPHER, are there any other ways to do this in an efficient manner?
Relationship types cannot be parameterized or specified dynamically in Cypher. If you have a defined set of relationship types there is a workaround. You can use a CASE statement to compare relationship types, populate an array if the relationship type matches, then iterate through the array(s) creating the correct relationship type:
LOAD CSV WITH HEADERS FROM 'file:///myfile.csv' AS line
MATCH (s:SemObject {sem_id: TOINT(line.ool_source_id)})
MATCH (t:SemObject {sem_id: TOINT(line.ool_target_id)})
WITH s,t,
CASE WHEN line.rlt_relation = "MEMBER_OF" THEN [1] ELSE [] END AS member_of,
CASE WHEN line.rlt_relation = "BELONGS_TO" THEN [1] ELSE [] END AS belongs_to
FOREACH (x IN member_of | CREATE (s)-[:MEMBER_OF]->(t))
FOREACH (x IN belongs_to | CREATE (s)-[:BELONGS_TO]->(t))