Laravel - using ID's to represent values in another table - php

I have two tables for my vehicles website:
I have a table in my DB which contains all car makes:
ID | name | display_name
1 | audi | Audi
2 | bmw | BMW
I also have a vehicles table:
ID | VRM | make
1 | HW55VRM | 2
2 | VN62HHS | 1
When editing a vehicle this is the method for creating the view:
public function edit($id)
{
$vehicle = $this->vehicle->getSingle($id);
$makes = $this->vehicle->getMakes();
$models = $this->vehicle->getModels();
return View::make('admin.vehicles.edit', compact('makes', 'models', 'vehicle'));
}
On this view I have a select box:
{{ Form::select('make',$models , NULL, ['class' => 'form-control']) }}
Which correctly creates a select box with the options I need. However, I want to set one of these values as selected depending on the table row data.
So the first vehicle in my DB has '2' as its make. Which represents a BMW.
How can I add that to my $vehicles variable in the cleanest way? So I can just do
$vehicle->named_make
for example.

If you have Eloquent models then provided you have proper relationships defined you can do like that
$vehicle->make->display_name

Related

Symfony Doctrine - retrieve records from a related table using the foreign key field

I have two related tables. One of the table has a one to many relationship to the second table. This is a sample illustration of the two tables
**
registration
id | firstname | membershipfk
1 | John | 2
2 | Foo | 3
**
Here is illustration of the second table
membership
id | type | discount | description
1 | Gold | xyz | xyz description
2 | Silver | xyz | xyz description
Now my present challenge is to retrieve the membership fields from the membership table using the foreign key in the registration table.
For example: Select Type, Discount and Description from Membership Entity where fk in registration entity is equal to 2
Presently in my controller I am making this attempt
public function getMembersAction()
{
$restresults = $this->getDoctrine()->getRepository('XXXBundle:Members')->findAll();
$data = array();
foreach ($restresults as $restresult) {
array_push($data, $this->serializeData($restresult));
}
Every kind assistance is much appreciated
Try with the following code
$em->getRepository('XXXBundle:Members')
->createQueryBuilder('m')
->select("m.type, m.discount, m.description")
->innerJoin("XXXBundle:Registration","r","WITH","m.id = r.membershipfk") //Here you will Join with the Registration Bundle
->where("m.id = 2")
->getQuery()
->getResults();
you need to call a findBy for example if your entity are set well.
Try this:
$results = $this->getDoctrine()->getRepository('XXXBundle:Members')->findByMember($memberId);
But you need to have configured well your entity first

How to fetch data from multiple tables using Join and where clause

I have written a simple symfony controller where I have two table known as specialtyarea and physician.
this is the basic structure of the table
specialtyarea
-----------------
id | name |
-----------------
1 | dentist |
2 | physician |
Physician table is related to specialtyarea as shown:
Physician
--------------------
id | name | specfk |
--------------------
1 | John | 1 |
2 | Doe | 2 |
3 | Ann | 2 |
I am trying to fetch all the physician where specialty area is 2
This is my snippet of code
public function getAllPhysicianAction($specId)
{
$id = $this->getDoctrine()->getRepository('Bundle:SpecArea')
->find($specId); //assuming that this returns all the id from the specialty table
$allPhysician = $id->getPhysician()->... //kind of lost here
}
How can I retrieve all the records from the physician table using the specialty Id?
I believe that you can just call findBy on your physician repository.
/**
* #Route("/physicians/{specId}", name="getAllPhysician")
*/
public function getAllPhysicianAction($specId)
{
$allPhysician = $this->getDoctrine()
//call the repository of your physician table
->getRepository('Bundle:physician')
->findBy(['specfk' => $specId]);
var_dump($allPhysician);
}
Use the findBy() method of the "physician" repository:
(You didn't post your actual entities so I'm guessing the field/entity names.)
$spec = $this->getDoctrine()->getRepository('Bundle:SpecArea')->find($specId);
$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $spec]);
You can also use $specId ID directly instead of fetching the entire entity from database:
$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $specId]);
See: Working with Objects - Querying - By Simple Conditions

Laravel: duplicate entries in foreach statement

I have a list feature that allows users to add specific articles to personalized lists. If i add more then one article to the same list. the list gets duplicated in the dropdown menu.
Example:
The more articles i add to the specific list. so it duplicates.
Database Tables
list | id | person_id | name | description
| 1 15 | Test List | null
data_list_ref | id | list_id | data_uid
| 1 | 1 | 9b888e1e9e
| 2 | 1 | jZ-mAtgh
Query
$lists = DB::table('list')
->leftJoin('data_ref_list', 'data_ref_list.list_id', '=', 'list.id')
->select('list.id', 'list.name', 'data_ref_list.data_uid')
->where('person_id', Auth::user()->person_id)
->get();
Blade Implementation
$record->key is the current 'article' being viewed in the browser
#foreach($lists as $list)
#if($list->data_uid === $record->key)
// show the checked list
// user's cant add the same article twice to a specific list
#else
// show the user's other lists
#endif
#endforeach
Try using Eloquent: Relationships.
Create 2 Models https://laravel.com/docs/5.3/eloquent#defining-models
One for "list" and one for data_list_ref.
In the model "list" create a relationship with "data_list_ref" https://laravel.com/docs/5.3/eloquent-relationships#defining-relationships
include the model in your Controller like this
use App\List;
Now if you want to get the data from "List" and also from "data_list_ref" you call it like this
$list = List::where('person_id', Auth::user()->person_id)->get();
This is laravel's way of getting data.

Right relationships in Laravel

hello, sorry for my english. I will try explain my problem.
For example, we have model Product.
Each product has some options:
product_1 : option_1 = 50, option_2 = 14, option_3 = 23
Whats is the right way?
First - create database, like
id | title | option_1 | option_2 | option_3
Second - create models and tables, like
ProductModel hasMany optionModel
OptionModel belongsToMany ProductModel
tables in databases: Product, Option, Product_Option_Relationships
Third - create some collection in function and table Product_Option_Relationships like
$options = collect([
['id' => '1', 'name' =>'option1'],
['id' => '2', 'name' =>'option2'],
]);
Table: id | product_id | option_id
Or maybe exist normal way, because first - its too big table, when you have 20 options, second - create new model only for information function, i dont now, its normal? Third - too difficult in view show options name.
Thank you, i hope you understand me.
Generally use the one-to-many, many-to-many relationships
And the benefit for that you can freely edit any record without modifying the whole column to apply that on your tables :
First we have products table which is going to require options foreach
so we should have the table options which is going to combine the options in general then we add a new table assignOptionsToProducts which is include keys for both options & products in this case you're going to have many-to-many or one-to-many relationship as you like
Products Table
id | Name
1 | Product A
2 | Product B
Options Table
id | Name
1 | Option A
2 | Option B
AssignOptionsToProducts Table
id | Product_id | Option_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 2
As you can see we assigned the same option many times
And when we want to modify any option you can without modifying each record in other tables and of course you can use each table many times easily
Use the second way. You won't have repeated options. For example:
products
id | name
---|------
1 | Car
2 | Bike
options
id | name
-----|------------
1 | Transport
option_product
option_id | product_id
------------|-------------
1 | 1
1 | 2
Using the other ways, you would have the option Transport twice.
You can use many-to-many relationship and can structure it like so:
Product Model
class Product extends Model {
...
public function options() {
return $this->belongsToMany('App\Product', 'product_options', 'product_id', 'option_id');
}
}
Options Model
class Option extends Model {
...
public function product() {
return $this->belongsToMany('App\Option', 'product_options', 'option_id', 'product_id');
}
}
You will need three tables for this to work:
Table products
id | name
-----------------
1 | iBeacon
2 | Intel Edison
Table options
id | name
----------
1 | Price
2 | Size
Table product_options
id | option_id | product_id
---------------------------
1 | 1 | 2
2 | 2 | 2
You can choose if you want to store a record with the option value in the options table or in the pivot table. I'd place them in the pivot table to keep the options table smaller.
Now you'll be able to assign options to your products like so:
...
// Assing options to a product
$product->options()->sync([$optionID, $optionID]);
// Get product's options
$product->options;
// Get products having certain option
$option->products;
...

Laravel - Use ID's to represent car makes in a vehicle field but return the full name in view

Is this classed as a belongs to / belongstomany / hasmany etc?
I have a table in my DB which contains all car makes:
ID | name | display_name
1 | audi | Audi
2 | bmw | BMW
I also have a vehicles table:
ID | VRM | make
1 | HW55VRM | 2
2 | VN62HHS | 1
What I wish to do is when returning all of the vehicles in my repository like so:
public function getAll()
{
return Vehicle::all();
}
What I wish to do is convert the make value to match that in the makes table and return the display name for it. So in my view I can simply call the display name as the text value.
You didn`t show relations between vehicles and makers, so for example it is like
class Vehicle
{
public function maker()
{
return $this->hasOne('Makers');
}
}
Then in blade
#foreach(Vehicle::with('maker')->get() as $vehicle)
{{ $vehicle->maker->display_name }} {{ $vehicle->VRM }}
#endforeach

Categories