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

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;
}

Related

Laravel custom query for answer and question database

I have three table called exams, questions and answers. They are connected via foreign id. I have function which i join questions and answers table. I have 1 question and multiple answers. When i join i see many same questions with 1 answer (which is normal). Is there any way to make join 1 question and multiple answers in one query(array) via query builder
Exams table
$table->id();
$table->string('language_code');
$table->string('title');
$table->integer('subcategory_id')->nullable();
$table->string('section');
$table->string('class');
$table->string('subject')->nullable();
$table->string('time')->default('60');
$table->timestamps();
Questions table
$table->id();
$table->integer('exam_id');
$table->string('q_pic')->nullable();
$table->string('q_name')->nullable();
$table->string('q_text');
$table->timestamps();
Answers table
$table->id();
$table->integer('user_id');
$table->integer('question_id');
$table->text('user_answer')->nullable();
$table->integer('user_answer_id');
$table->integer('c_answer_id');
$table->timestamps();
And here is my view function
public function view($id)
{
$questions = DB::table('questions')
->leftJoin('answers','answers.question_id','=','questions.id')
->where('questions.exam_id','=',$id)
->get();
return view('main/view',compact('questions'));
}
If you set up the relationships right, you would not need a join to achieve this.
Your relationships should look like this:
Exam model:
public function questions()
{
return $this->hasMany(Question::class);
}
Question model:
public function exam()
{
return $this->belongsTo(Exam::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
Answer model:
public function question()
{
return $this->belongsTo(Question::class);
}
Now you can query like this:
//use App\Question;
$questionsWithAnswers = Question::where('id', $id)->with('answers')->get();
This should give you a collection of questions with related answers.

Laravel 5 Eloquent - whereIn on join table [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 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();
}

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 is the easiest way to add cities and countries of the world to an HTML5 form? [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'm creating a form, and I would like to allow the user to choose their country, and their city. What is the most effective way to do it?
For things like state and country, the possible number is reasonably small enough that you can build dropdowns for this without too much hassle. Here is a plugin for jQuery that has a "country picker" pre-made, and you can easily find the same for State on Google.
When you start talking about cities, there are a vastly large number of them. In my opinion, you're far better off using a simple textbox for this and letting the user fill it in themselves.
EDIT
Here is an example of building a country list from a database in MVC:
Country class (Model)
//This class represents a Country
public class Country
{
public int CountryID { get; set; }
public string CountryName {get; set; }
public Country(int countryID, string countryName)
{
this.CountryID = countryID;
this.CountryName = countryName;
}
}
Controller
List<Country> countries = new List<Country>(); //Create a list of Country objects
IEnumerable<SelectListItem> countryList; //List to hold the values for the dropdownlist
SqlConnection connection = new SqlConnection(connectionString); //build a connection with your connection string
connection.Open();
SqlCommand query = new SqlCommand("SELECT CountryID, CountryName FROM Country", connection); //query the table
query.CommandType = CommandType.Text;
SqlDataReader reader = query.ExecuteReader(); //execute the query
while (reader.Read()) //read out the results, set each result to a Country object
{
Country country = new Country(
Convert.ToInt32(reader["CountryID"]),
reader["CountryName"].ToString());
countries.Add(country); //add to the initial list
}
connection.Close();
//build the list of <SelectListItem>s to pass to the view
countryList = countries.Select(c => new System.Web.Mvc.SelectListItem
{
Text = c.CountryName,
Value = c.CountryID.ToString()
});
ViewBag.CountryList = countryList; //add the list to ViewBag
And the View
#Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.CountryList, "Value", "Text"), new { #class = "formItem" })
This code hits your database for the list of countries and builds a List<Country> from the SqlDataReader. Then we turn these results into a List<SelectListItem> to pass into the view.
The result is a dropdown list that will always contain whatever records are in your database. If you add/remove items, the list will be representative of this.
The #Html.DropDownListFor(x => x.ID) binds the selected Value to the model's ID property, so you simply select this value on POST. (Note that your model will need to contain an ID property for this to work!
EDIT to emphasize the "fun" of making a city selector:
I really, really advise against trying to build a city selector. Check out the list of cities in Kansas (something I picked at random). I didn't bother to count these, but this is a pretty big list, and that alone is one state in one country in the world.
If you went with a database, you'd easily have thousands of records for the United States alone, and that only leaves you with 195 other countries to build data for.
Perhaps you can find a repository that already has this information available, but the amount of work required to make this happen seems prohibitive.

How insert very reference in doctrine

I have 3 entities: User, Page, Post
In the Post entity:
class Post
{
/**
* #ORM\ManyToOne(targetEntity="Page")
*/
private $page;
/**
* #var ArrayCollection $subscribers Specify users that see this post.
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="wallPosts")
*/
private $subscribers;
}
In the Page enity:
class Page
{
/**
* #ORM\ManyToMany(targetEntity="User")
*/
private $members;
}
When a post is published I want that all users that are members of Page are set as subsribers of Post
$post->setSubscribers($post->getPage()->getMembers())
note: Page can have several thousand users, what is best way that have best performance? Should I use a native query, database triggers or procedures?
You can do it in cycle. Subscribe 50 users per one iteration to new post.
Do not forget to clean doctrine internal storage. The main idea is
$page = $post->getPage();
for ($i = 1;; ++$i) {
$members = $page->getPagindatedMembers($i);
if (empty($members)) {
break;
}
foreach ($members as $member) {
$post->addSubscriber($member);
}
$em->flush();
$em->clear(Member::class);
}