Laravel 5 Eloquent - whereIn on join table [closed] - mysql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create an online directory, where, for example, people can search through the website and find all takeaways that have a specific type. For example:
"Indian",
"Chinese"
etc..
I have 3 tables:
Business
Tags
Business Tags
And my model is as follows:
class Business extends Model
{
protected $table = 'businesses';
protected $fillable = [
'business_name', 'postcode'
];
public function tags()
{
return $this->belongsToMany('App\Tags');
}
}
The issue is, whenever I come to do the search, and try to do a whereIn the issue is that it takes forever to load, in fact, it doesn't even load. For example:
$business = Business::whereHas('tags', function($tag) use ($request) {
if($request->get('terms'))
{
$tag->whereIn('tags.name', ['chinese']);
}
})->get();
So my question is this:
I have just over 10k rows of data stored inside the table. This table is split into three "Business", "Tags", "Business Tags". The process above is taking so long to complete, probably because I use the whereHas('tags') and whereIn therefore, how do I go about using the following syntax:
$business = Business::where( function ($business) use ($request) {
// Search for businesses with a specific tag, passed from request
});
Is this possible?

I'm just wild guessing here, but try to pull the condition outside of the function and don't specify the name of the table:
if($request->get('terms'))
{
$business = Business::whereHas('tags', function($tag) use ($request) {
$tag->whereIn('name', ['chinese']);
})->get();
}

Related

#1146 - Table 'crud_app.names' doesn't exist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am following this tutorial here, crud app with node js and mysql.
My database, crud_app has a table named crud_table, and crud_table has got 3 columns, id, names, and date_added.
I am trying to make a SQL query using node js
async getAllData() {
try {
const response = await new Promise((resolve, reject) => {
const query = "SELECT * FROM names"
connection.query(query, (err, results) => {
if (err) { reject(new Error(err.message))}
resolve(results)
})
});
console.log(response);
return response;
} catch (error) {
console.log(error)
}
}
But I get this error
Error: ER_NO_SUCH_TABLE: Table 'crud_app.names' doesn't exist
And again I went to PHPMyAdmin to run this query in the console.
SELECT * FROM names
Output
It is claiming that the names column does not exist but you can clearly see the column here
Is there any way I can resolve this problem?
Your table name is crud_table and within your table you have the column names. You cant select all the date from a column by using SELECT * on the column,with SELECT you select data from your table in your case crud_table,so if you want all the names then try this "SELECT names FROM crud_table"

Is there an NPM package to log a SQL database in node? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm making an app that retrieves information from SQL databases and displays the info in node, but I'm a bit stuck in trying to find a way to print the entire table as a table instead of the loose individual data. Is there an npm package that might do this that you might recommend? If not, is there an obvious way to do this I'm not seeing?
Thanks for the help.
I've used https://www.npmjs.com/package/table for this. See example for logging mysql output ( I'm using it in my simple mysql repl - https://github.com/sidorares/myki ):
const connection = mysql.createConnection(Object.assign({}, config, { rowsAsArray: true }));
const chalk = require('chalk');
function myEval(cmd, context, filename, callback) {
connection.query(cmd, (err, rows, fields) => {
if (err) {
if (!err.fatal) {
console.log(chalk.red(err.message));
return;
} else {
return callback(err);
}
}
console.log(
table([fields.map(f => chalk.bold(f.name))].concat(rows.map(r => r.map(c => util.inspect(c, { colors: true })))))
);
callback(null);
});
}

database normalization do I need it [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've read a lot about normalization and I still can't fully understand it/I'm not sure how to normalize this. This is how my database currently looks, does it even need to be normalized? If so, where do I even start?
http://i.imgur.com/L43fHS6.png this is what it currently looks like
You will want to have 1 row per user_ID so you can easily access all the data.
e.g. for your gameID 5002947 (row11) this needs to be split into the following:
id setup_id user_ID
5002947 997 563749
5002947 997 500243
5002947 997 536271
...
You have two options. Create a complex SQL query that will handle this (I can't supply this unfortunately but I'm sure others could) or use php.
PHP method
Select all rows and explode the userID into an array.
loop through this array and insert back into the database.
Depending on the number of rows and userIDs you have this may take a while to execute.
e.g.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$query = 'SELECT * FROM table';
$data = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_array($data))
{
$data[] = array("gameid"=>$row['game_ID'], "setupid"=>$row['setup_ID'],"userid"=>str_getcsv($row['user_ID'])); /*And all your other information*/
}
for($i=0; $i<count($data); $i++) {
$gameid = $data[$i]['gameid'];
$setupid = $data[$i]['setupid'];
/*Other info you need*/
for ($x=0; $x<count($data[$i]['userid']);$x++) {
$userid = $data[$i]['userid'][$x];
if ($stmt = $mysqli->prepare("INSERT INTO newtable (game_ID, setup_ID, user_ID) VALUES (?, ?, ?)")) {
$stmt->bind_param('iii', $gameid ,$setupid ,$userid);
if (!$stmt->execute()) {
$stmt->close();
}
}
}
}

What will be the best practice which I should use? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am newbie in Symfony2.
I have table in which exists 5 columns: answer_a, answer_b, answer_c, answer_d and correct_answer.
Answers a-d contain text answer in ABCD quiz. In correct_answer I have "a", "b", "c" or "d" string. How I can in the best possible way show user correct text answers? I should add to entity new "text_correctanswer" field? Or I should create in controller new array with correct text answers?
You need oneToMany relationships
Documentation with examples
use Doctrine\Common\Collections\ArrayCollection;
/** #Entity */
class Quiz {
protected $id;
/**
* #OneToMany(targetEntity="Answer", mappedBy="quiz")
*/
protected $answers;
public function __construct()
{
$this->answers = new ArrayCollection;
}
}
/** #Entity */
class Answer {
protected $id;
protected $isCorrect;
/**
* #ManyToOne(targetEntity="Quiz", inversedBy="answers")
* #JoinColumn(name="quiz_id", referencedColumnName="id")
*/
protected $quiz;
}

Get a particular page content from old_text column [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What I am trying to do is to get a telephone contact list from a page content.
All my pages are stored in a database, which I have successfully accessed using Code Igniter.
I want to output a telephone contact list as HTML table. This list is located on one of the pages. The content of this page is saved as BLOB type in the old_text column of the table text in my MySQL database.
I know the old_id value of my page in the table text. I think it might be useful.
How can I find this contact list using MYSQL commands in php script?
Here is my code how I have selected the old_text value of the page where the telephone contact list is.
Code Igniter Controller:
class Site extends CI_Controller{
public function index(){
$data['record'] = $this->db->query('SELECT old_text FROM text WHERE old_id = 862');
$this->load->view('home',$data);
}
}
Code Igniter View home.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="container">
<?php print_r($record);?>
</div>
</body>
</html>
And I have got as an output:
CI_DB_mysql_result Object ( [conn_id] => Resource id #28 [result_id] => Resource id #29 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => 1 [row_data] => )
The reason for this output in my oppinion might be the fact that the old_text content as BLOB type encoded is.
I have also tried the following command in order to return BLOB field as a varchar, but I have got the same output.
SELECT cast(old_text AS char) FROM text WHERE old_id = 862
As you can see in the output, $data['record'] is a CI_DB_mysql_result Object.
So you will "get" data from this object. Assuming you only have 1 result you have to do:
class Site extends CI_Controller
{
public function index()
{
$res = $this->db->query('SELECT old_text FROM text WHERE old_id = 862');
if ($res->num_rows() > 0)
{
$data['record'] = $res->row();
}
else
{
$data['record'] = "no result";
}
$this->load->view('home',$data);
}
}
If you have multiple result you have to loop on the $res.
You can take a look at http://ellislab.com/codeigniter/user-guide/database/results.html