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.
Related
I am trying to building ecoommerce system using laravel 9. Everything goes fine but Suddenly I got one issue. I want to show product based on category id but my product table category id store multiple. Bellow I am showing my table structure:
Product Table:
|---ID---|---Name---|---Cat_id---|---Status--|
| 1 | T-shirts | 1,2, | active |
| 2 | Pants | 4,3, | active |
| 3 | Sweaters | 5,2, | active |
Category Table
|---ID---|---Name---|
| 1 | General |
| 2 | News |
| 3 | Festival |
| 4 | Category |
Controller
public function category($slug)
{
//
$cat = Category::where('slug', $slug)->first();
$products = Product::whereIn('cat_id', [$cat->id])->where('status', 'active')->orderby('id', 'asc')->paginate('12');
return view('frontend/Catproducts', compact('products', 'cat'));
}
Now I want when I am click on "NEWS" category I want to see two product. How can I fix it
As #aynber said in the comments, best solution is to normalize the database, so you have a setup like this:
Categories table:
id
name
Products table:
id
name
status
Product_categories table:
id
product_id
category_id
With a belongsToMany relationship from Product to Category(and back), your query should look something like:
$categoryIdArray = [2];
Product
::whereHas('category', function($query) use($categoryIdArray) {
$query->whereIn('id', $categoryIdArray);
})
->get();
It is still possible with your current setup though, while a little hacky:
$cat = Category
::where('slug', $slug)
->first();
$catId = $cat->id;
$products = Product
::where(function($where) {
$where->where('cat_id', 'like', "$catId,%")//Look for first cat in col, don't forget trailing comma
->orWhere('cat_id', 'like', "%,$catId,%")//Look for appended cat between commas
})
->where('status', 'active')
->orderby('id', 'asc')
->paginate('12');
This will work on small scale, but because we are using like, mysql needs to check ALL records, and cannot optimize the query. That's the reason why normalization is important :)
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
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;
...
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
I have these tables in my database, namely "airport" and "route", the id of "airport" is a foreign key in "route" (i.e. Origin, Destination).
Airport
+-------+-------------+-----------------------+
| id | airportcode | Location |
+-------+-------------+-----------------------+
| 1 | CEB | Cebu |
| 2 | MAN | Manila |
+-------+-------------+-----------------------+
Routes
+-------+-------------+-----------------------+
| id | Origin | Destination |
+-------+-------------+-----------------------+
| 1 | 1 | 2 |
| 2 | 2 | 1 |
+-------+-------------+-----------------------+
So far, this is my query in my Controller and it's only returning the "Origin, Destination"
DB::table('airport')
->join('route', 'airport.id','=','route.Origin')
->join('route', 'airport.id','=','route.Destination')
->select('route.Origin', 'route.Destination')
->get();
What I would like to do is this:
SELECT 'airport.Location' from airport, route WHERE 'route.Origin' = 'airport.id' AND 'route.Destination' = 'airport.id".
Any suggestions will do!
So - you want to pull out the model for a specific airport id but only if it goes to the specified destination?
Your first query will only return the two columns as that's what you told it to return
You can get the airport easily by:
Airport::find($id);
Where $id is the id from a user input for example and should be the key. Find will return a collection
You could also do:
Airport::where('id','=', $id)->first() //will return the first record - you could also use ->get() to return a collection
Then if you have a join in your Airport model such as ->hasMany you could then do:
Airport::where('id','=', $id)
->with('routes')
->get()
Which will return the airport with the related routes model attached to it
You can then take that a stage further and query the relationship by:
Airport::find($id)->routes()->where('destination','=',$dest_id);
I think that should do the trick - as long as you create the relationship correctly in the models
If you are using a select query make sure that you have mentioned all the fields you want...
it's only returning the "Origin, Destination" because you have mentioned only those two in your select query.
try something like...
DB::table('route')
->select('route.Origin', 'route.Destination','airport.Location')
->leftjoin('airport', function($join)
{
$join->where('airport.id',array('route.Origin','route.Destination'));
// I haven't used it, if any errors pls comment
})
->get();
hope this helps you...