Products table structure
My API should return values (not ids) and that is what i need. In PHP i just did queries to search tables for values, i guess in laravel way for that is close but i am new in this framework and need little help ;]
I was searching and construct something like this :
$products = Products::all();
foreach ($products as $key => $product) {
$product->id_Model = DB::table('models')->select('model')->where('id', '=', $product->id_Model)->get();
}
"models" table contains names
"products" table contains ids of "models" -> products.id_Models = models.id
I i said above my API result should be names instead of ids so i need to search for name of every product before i put it into json.
Ok i get to point i wanted to be result of work
API :
https://prnt.sc/i8cy9w
DB :
https://prnt.sc/i8cytv
Values ale "fake" ones from Seeders, now i only need to fix doubles
/edit
Fixed now it works well :
https://prnt.sc/i8d4u5
example line: $product->id_Colors = DB::table('colors')->select('color')->where('id', '=', $product->id_Colors)->value('color');
Related
im new in laravel programming and im trying to do something with laravel Eloquent.
So i have 3 tables, dev, dev_project(many to many) and project.
i need to see in which projects the dev is part of, using the dev_project table, and get the corresponding id from projects.
after that i need to go to the table project, and use the id that I got from the many-to-many table to get the corresponding name of the projects in which that same dev is part of.
First im fetching data from my DB into a variable
$devproject = DB::table('dev_project')->where('id_dev', '=', Auth::user()->id)->get();
And then Im trying to get the data from the project table where the id is the same from the one that i fetched before
return Project::where('id', $dev_project->id_project);
The problem here is that the variable dev_project is an object, and i cant use a foreach and store the data that i want to return inside an array.
So how can I get all the data that i want in the same object.
I appreciate any help, Thank you.
Here, $devproject is a Collection, not a single row. $dev_project->id_project is not a valid property.
If you want the first result's id_project, then the syntax is $devproject->first()->id_project.
If you want a Collection of each of $devproject 's id_project, then the syntax should be $devproject->pluck('id_project').
With that in mind, your query should either be
return Project::where('id', $dev_project->first()->id_project);
or
return Project::whereIn('id', $dev_project->pluck('id_project'));
As harish durga suggests, a relationship would save you the trouble of writin these queries.
# Dev Model
public function projects()
{
return $this->belongsToMany(Project::class, 'dev_project', 'id_project', 'id_dev');
}
# Project Model
public function devs()
{
return $this->belongsToMany(Dev::class, 'dev_project', 'id_dev', 'id_project');
}
# Get all devs with associated projects:
$devs = Dev::with('projects')->get();
foreach ($devs as $dev) {
echo $dev->...
foreach ($dev->projects as $project) {
echo $project->...
}
}
Good day. I am building an API, in which I want to return some data. I have three tables
counsels
counsel_cases
analysis_sc
A section of the counsels table is shown below
A section of the counsel_cases is also shown below
Finally, a section of the analysic_sc is shown below.
I want that when a counsel is selected, through the counsel_id, I can fetch the cases belonging to the counsel from the counsel_cases, and then with that information, I want to be able to fetch the number of cases of such a counsel belonging to a legal head (area of practice) on the third table as shown in the design below.
How will that be possible. I have a relationship between counsel and counsel_cases though. Also, I have tried using a foreach loop as shown below, but I am unable to get the unique values of the legal_head.
public function getCounselPracticeAreas(Request $request)
{
$counsel_id = $request->route('counsel_id');
$cases = CounselCase::select('suit_number')->where('counsel_id', $counsel_id)->get();
$data = [];
foreach ($cases as $case) {
$values = AnalysisSc::select('legal_head')->where('suitno', $case->suit_number)->first();
array_push($data, $values);
}
return response()->json([
"message" => "successful",
"data" => $data
]);
}
However, this is the value I get
[![enter image description here][5]][5]
I want to get something like this:
$data : [
"legal_head" : [
"name" : "Criminal Law",
"count" : 2
]
]
Please, is this possible
I know this is quite long. And I hope I explained myself well. Thanks
you need to use SQL Joins to create a relationship between the tables and fetch the data
It looks like you're skipping using relationships in your models. Once you have your models set up, retrieving the data you need will be a lot easier with Laravel. You may want to separate your models/tables a little more and add relationships, like the following:
Models/tables:
Counsel (counsels)
id
name
LegalHead (legal_heads)
id
name
Case (cases)
id
suit_number
year
subject_matter
legal_head_id
case_counsels (This is not a model, just a relationship table)
id
case_id
counsel_id
appearing_for
role
Note: I wasn't sure how your data is structured. You can use this as start and adjust as necessary.
Relationships
The Many-Many relationship is suitable for the case counsels and you'll be able to add the role as a pivot(extra field) for the relationship.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
Case
legal_head: belongsTo
counsels: belongsToMany with pivot for role
Counsel
cases: belongsToMany with pivot for role
Retrieving the Objects
When that is set up, you won't have to do as much query work. You can do this to get case data with counsels, legal_head and their role for each case:
$cases = Case::with('counsels','legal_head')->get();
And this to get the Legal Head names with the number of cases:
$legal_heads = LegalHead::withCount('cases')->get();
I'm having a little problem with laravel that may be easily solved. To be short, the situation is: I have two tables, one for the users and the other one for products that has a column 'user_id' so I can identify the associated user.
In Laravel, I can use
$user = Sentry::getUser(); //Or Auth::user() if you're not using Sentry
$products = DB::table('table2')->where('user_id',$user->id);
And that should give me every product that user has. Good.
Now I want to show the products individually on screen, but unfortunately that doesn't work. It seems I can't echo this information in a string because it's made of multiple rows. I get
Object of class Illuminate\Database\Query\Builder could not be converted to string
For the solution, since the maximum associated products I allowed in the system is 3, I came up with the idea of getting each row separately and echoing them. For the first one, it's simple: $products->first(); but I have no idea on how to get the other two.
And maybe I'm being a newbie here, but I don't think I can use the products' id info since $products->id returns an error.
Can anyone help me?
Thanks in advance!
You want to use take, limit the number of results to three and then print out every one with a foreach loop. Docs: Laravel Queries, see skip and take.
$products = DB::table('table2')->where('user_id',$user->id)->take(3)->get()
Then, inside your view, you can just iterate through this data:
#foreach($products as $p)
Alternatively, in your PHP you can iterate through this data using something like:
foreach ($products as $product) { var_dump($product); }
(You are getting that error because you are trying to output a result object as a whole, and not the data it contains. Using the loop actually fetches the data from the result object so you can then use the loop variable ($product) normally.)
To get data from database you can use one one those methods: all, get, or first.
Using all:
$products = DB::table('table2')->all();
you are getting all the products.
Using first you can use conditions but you will get only first record that fulfil conditions:
$products = DB::table('table2')->where('user_id',$user->id)->first();
Using get you can use conditions and you will get all the records that fulfil those conditions:
$products = DB::table('table2')->where('user_id',$user->id)->get();
So in your case you want to use get to get data from database.
When you are using
$products = DB::table('table2')->where('user_id',$user->id);
Then $products is an array and you do not have to echo an array.
To display the products you need to use a foreach loop like below
foreach ( $products as $key => $product ) {
var_dump( $product );
}
If you want to show only three products, then you can use for loop inside foreach.
You can learn more about foreach from below link
http://php.net/manual/en/control-structures.foreach.php
I started using Laravel yesterday, the ORM seems powerful. Does it have any way of updating rows in related models? This is what I tried:
Step 1: Generate a JSON object with the exact structure the database has. The JSON object has certain fields that are subarrays which represent relationships in the database.
Step 2: Send the JSON object via POST to Laravel for processing, here it gets tricky:
I can change the JSON object into an array first
$array = (array) $JSONobject;
Now I need to update, I would expect this to work:
Product::update($JSONobject->id,$array);
But because the array has subarrays, the update SQL that is executed cannot find the sub-array column in the table, it should instead look for the associated table. Can this be done? Or do I have to call the other models as well?
Thanks in advance!
This is something that Eloquent does not handle for you. The array that you supply to the update() method should contain columns only for, in your case, the Product model. You might try something like this to update relations. This is all off the top of my head and is by no means tested. Take it with a grain of salt.
$update = (array) $JSONobject;
$relations = [];
foreach ($update as $column => $value)
{
// If the value is an array then this is actually a relation. Add it to the
// relations array and remove it from the update array.
if (is_array($value))
{
$relations[$column] = $value;
unset($update[$column]);
}
}
// Get the product from the database so we can then update it and update any of the
// the products relations.
$product = Product::find($update['id']);
$product->update($update);
foreach ($relations as $relation => $update)
{
$product->{$relation}()->update($update);
}
The above code assumes that the key for your nested relation arrays is the name of the relation (method name used in your model). You could probably wrap this up in a method on your Product model. Then just call something like Product::updateRecursively($JSONobject); I'm terrible with names but you get the idea.
This probably won't work with more complex relations either. You'd have to take it a few steps further for things like many to many (or probably even one to many).
I'm wondering if Yii has an efficient method for grouping items by type.
Let's say I have the following model:
Tag
------
id
name
type_id
And let's say there are 5 different types of Tags. I want to be able to display in my index all tags in sections by type_id. Is there a Yii-way of accomplishing this?
Outside a framework I would write a function such that results fetched from the DB were stored like this:
$tags[$typeID][] = $tag;
Then in each section I could do something like:
foreach( $tags[$typeID] as $tag )
{
// Here are all tags for one $typeID
}
But I'm having difficulty figuring out how to do this in Yii without:
A) looping through the entire result set first and rewriting it or,
B) running 5 different queries.
When using ActiveRecord simply specify the "index" in the DBCriteria. So in a query do:
ActiveRecordClass::model()->findAll(array('index'=>'type_id'));
That will return an assoc array that your after. TBF it probably executes exactly the same code, but this is obviously easier to use that performing it everywhere.
Assuming that your active record class is called MyActiveRecordClass, the simplest approach should be sufficient:
$models = MyActiveRecordClass::model()->findAll();
$groupedModels = array();
foreach ($models as $model) {
$groupedModels[$model->typeID][] = $model;
}
If you give more specific information about how you intend to display the grouped results it might be that a better approach can be worked out.