I have tabel like this
id name parent_id order_id
1 software 0 1
2 hardware 0 2
3 windows 1 3
4 linux 1 4
5 mouse 2 5
6 keyword 2 6
And I use Laravel 5.1 Eloquent
How to get data in model like this
[{"id":1,"children":[{"id":3},{"id":4}]},{"id":2,"children":[{"id":5},{"id":6}]}]
There is a best way to do this.
The package etrepat/baum is so awesome and easy. It has everything you need about nesting elements. Just add it to your composer dependencies and enjoy.
You can also add these methods to your Model and use them as relations.
public function parent() {
return $this->belongsTo(self::class, 'parent_id');
}
public function children() {
return $this->hasMany(self::class, 'parent_id');
}
Then you will simply say:
$results = MyModel::with('children')->get();
Update for comment:
$results = Category::select('id','name')->with([
'children' => function($query) {
$query->select('id', 'parent_id');
// You can customize the selected fields for a relationship like this.
// But you should select the `key` of the relationship.
// In this case it's the `parent_id`.
}
])->get();
Related
I'm trying to find a way to do \App\Goal::find(1)->children and get returned all children, and childrens children.
With the database pasted below I want
\App\Goal::find(1)->children
to return
2, 4 and 5. Currently I can only do \App\Goal::find(1)->goals, which returns only 2 and 4
I have a database like this:
id user_id goal_id objective
1 1 NULL Get rich
2 1 1 Save $5
3 1 NULL Learn to cook
4 1 1 Save $10,000
5 1 4 Buy stocks
6 1 5 Buy 5x Intel
7 1 5 Buy 5x AMD
How would you go about creating the children() function in the Goal model?
Please ask if any important info is missing from this
Edit:
Goal.php:
public function user()
{
return $this->belongsToUser(User::class);
}
public function goals()
{
return $this->hasMany(Goal::class, 'goal_id')
}
When I run \App\Goals::find(1)->goals in the GoalController it returns the children of itself (with id 2 and 4 from the example db table), but not its grandchildren...
ID 5 from the example table has a parent of id 4, which itself has a parent id of 1.
So how could I get \App\Goal::find(1)->children or \App\Goal::find(1)->goals to return its grandchildren, and their children etc?
So, assuming the table you've posted is the goals table, related to App\Goal...
If you have these two relationships set up on the model:
public function children()
{
return $this->hasMany(Goal::class, 'parent_id');
}
public function childrenRecursive()
{
return $this->children()->with('children');
}
You can call Goal::with('childrenRecursive')->get() which will return a nested collection of all the children and children's children.
If you'd like all of the children in a flat array, you could do something like this:
public function getFamilyAttribute()
{
$family = collect([]);
$children = $this->children;
while (!is_null($children )) {
$family->push($children);
$children = $children->children;
}
return $family;
}
I want to get all the vouchers that have at least one child, a voucher can have multiple voucher children, but any voucher can only have one parent.
I set it up with the following models and calls, and the query it generates is as desired, until this part: 'vouchers'.'parent_id' = 'vouchers'.'id'
Wanted functionality:
$vouchers = Voucher::has('children')->get();
or
$vouchers = Voucher::has('parent')->get();
Resulted Query
select * from `vouchers` where `vouchers`.`deleted_at` is null
and (select count(*) from `vouchers` where `vouchers`.`deleted_at` is null
and `vouchers`.`parent_id` = `vouchers`.`id`
and `vouchers`.`deleted_at` is null ) >= 1
Models:
class Voucher extends baseModel {
public function parent()
{
return $this->belongsTo('Voucher', 'parent_id');
// return $this->belongsTo('Voucher', 'parent_id', 'id'); <- attempted but din't work
}
public function children()
{
return $this->hasMany('Voucher', 'parent_id');
}
}
This issue has been reported and fixed in 5.0 https://github.com/laravel/framework/pull/8193
Unfortunately there is no back port for the version 4.
However if you want to apply the fix yourself you can see the list of modifications here : https://github.com/laravel/framework/pull/8193/files
Be carefull, modifying the framework's code base is at risk but there will be no more bug fixes on Laravel 4.x version, only security fixes for a few more month.
In Laravel I just started with models and I have this database structure:
users
id | username | password | group | //(group is the id of the group)
groups
id | groupname |
group_pages
group_id | page_id | create | read | update | delete
pages
id | pagename
I am trying to check if the user can create/read/update/delete on the page he's on.
So I have 4 Models for this at the moment: Users, Pages,Group_pages and Groups. So in the models, I define the relationships like so:
User model:
public function group()
{
return $this->belongsTo('group', 'group', 'id');
}
Group Model:
public function users()
{
return $this->hasMany('users', 'group', 'id');
}
public function group_pages()
{
return $this->hasMany('group_pages', 'group_id', 'id');
}
I am using this in my controller like this:
$group_id = User::find(Session::get('user_id'));
$crud = Group::find($group_id->group)->group_pages()->first();
As described in the documentation.
but this is giving me the error:
Class group_pages not found
What is going wrong here?
I'm not sure about assigning the keys in the relationships.
I know this:
One to One Inverse:
return $this->belongsTo('class', 'local_key', 'parent_key');
One to Many:
return $this->hasMany('class', 'foreign_key', 'local_key');
I dont know about the One to Many Inverse. I know it's: return $this->belongsTo('table');, but I dont know about the keys.
Group_pages model:
class Group_pages extends Eloquent {
public function pages()
{
return $this->belongsTo('pages', 'id', 'group_id');
}
public function group()
{
return $this->belongsTo('group', 'id', 'group_id');
}
}
Model files should be named singularly and in camel-case, i.e. User, Page, Group. A model representing the join between users and groups isn’t necessary.
Then when it comes to defining the relationships, the first parameter is the class name of the model:
class User {
public function group()
{
return $this->belongsTo('Group', 'local_key', 'parent_key');
}
}
You’re making life difficult for yourself by going against Laravel’s conventions.
If you name your columns as per Laravel’s conventions, you then don’t need to specify them in your relationship definitions either. So your users table should have a column named group_id that’s a foreign key referencing the id column in your groups table. Your relationship can then be expressed like this:
class User {
public function group()
{
return $this->belongsTo('Group');
}
}
A lot more succinct and easier to read, and you don’t have to remember which way around the local and foreign column names go.
You can read more about the conventions Laravel uses for model and relation names in the official documentation: http://laravel.com/docs/master/eloquent#relationships
You defined your relationship with a model-class that does not exists.
To solve this, create a group_page-model (or even better GroupPage) and change the corresponding relationship (return $this->hasMany('GroupPage', 'group_id', 'id'); within your Group-model.
Then fix the relationship in your User-model:
public function group() // typo! not groep..
{
return $this->belongsTo('group', 'group'); // remove id, you do not need it
}
Then there is a problem with your controller code which might be fixable like that:
$group_id = User::find(Session::get('user_id'))->group()->id;
$crud = Group::find($group_id)->group_pages()->first();
I always like to recommend Laracasts to peopel who are new to Laravel (i hope you do not know this yet). The basic screencasts are all free (laravel 4 from scratch and laravel 5 fundamendals) and you will lern very fast in no time! Specifically, have a look at the episode on Eloquent Relationsships.
I also strongly recommend sticking to conventions
use the column-name group_id on the users-table for the group-foreign-key).
Classnames should be PascalCase -> Group, not group, and when commiting them as parametes, stick to it (belongsTo('Group'))...
This makes life much easier!
Finally
Be aware that there might be packages for what you are trying to achieve. One that comes to my mind is Entrust.
You're making your life hard with this code and thus you can't make it work.
Check this out first:
// This is User model, NOT group_id
$group_id = User::find(Session::get('user_id'));
Next:
public function group() // I suppose groep was typo, right?
{
// having relation with same name as the column
// makes Eloquent unable to use the relation in fact
return $this->belongsTo('group', 'group', 'id');
}
So, here's what you need:
// User model
public function group()
{
return $this->belongsTo('Group', 'group_id'); // rename column to group_id
}
// Group model
public function pages()
{
return $this->belongsToMany('Page', 'group_pages')
->withPivot(['create', 'read', 'update', 'delete']);
}
Then:
$user = User::find(Session::get('user_id')); // or use Auth for this
$page = $user->group->pages()->find($currentPageId);
// now you can access pivot fields:
$page->pivot->create;
$page->pivot->update;
... and so on
I have a many to many relationship for orders and products.
<?php
class Order extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
public function products()
{
return $this->belongsToMany('Product');
}
}
?>
<?php
class Product extends Eloquent {
public function orders()
{
return $this->belongsToMany('Order');
}
}
?>
Need to fetch the number of times each product is ordered.In mysql,this task can be achieved by using the following query
SELECT products.id, products.description, count( products.id )
FROM products
INNER JOIN order_product ON products.id = order_product.product_id
INNER JOIN orders ON orders.id = order_product.order_id
GROUP BY product_id
LIMIT 0 , 30
Result of the above query is as follows:-
id description count(products.id)
1 Shoes 3
2 Bag 2
3 Sun glasses 2
4 Shirt 2
How this task can be achieved using laravel eloquent (without using query builder)????How can i fetch the number of times each product is ordered using laravel eloquent??
For future viewers, as of Laravel 5.2, there is native functionality for counting relationships without loading them, without involving your resource model or accessors -
In the context of the example in the approved answer, you would place in your controller:
$products = Product::withCount('orders')->get();
Now, when you iterate through $products on your view, there is a orders_count (or, generically, just a {resource}_count) column on each retrieved product record, which you can simply display as you would any other column value:
#foreach($products as $product)
{{ $product->orders_count }}
#endforeach
This method produces 2 fewer database queries than the approved method for the same result, and the only model involvement is ensuring your relationships are set up correctly. If you're using L5.2+ at this point, I would use this solution instead.
Mind that Eloquent uses Query\Builder under the hood, so there is no such thing in Laravel, like 'query eloquent without using query builder'.
And this is what you need:
// additional helper relation for the count
public function ordersCount()
{
return $this->belongsToMany('Order')
->selectRaw('count(orders.id) as aggregate')
->groupBy('pivot_product_id');
}
// accessor for easier fetching the count
public function getOrdersCountAttribute()
{
if ( ! array_key_exists('ordersCount', $this->relations)) $this->load('ordersCount');
$related = $this->getRelation('ordersCount')->first();
return ($related) ? $related->aggregate : 0;
}
This will let you take advantage of eager loading:
$products = Product::with('ordersCount')->get();
// then for each product you can call it like this
$products->first()->ordersCount; // thanks to the accessor
Read more about Eloquent accessors & mutators,
and about dynamic properties, of which behaviour the above accessor mimics.
Of course you could use simple joins to get exactly the same query like in you example.
If you already have the $products object, you can do the following:
$rolecount = $products->roles()->count();
Or if you are using eager loading:
$rolecount = $products->roles->count();
Cheers.
I am using Laravel 5.1 and i am able to accomplish that by doing this
$photo->posts->count()
And the posts method in Photo model looks like this
public function posts(){
return $this->belongsToMany('App\Models\Posts\Post', 'post_photos');
}
I am setting up several Models an want to know the correct approach to table structure and Model relationships.
Let's assume we have a shop containing products, each with properties size and color.
Table products
id
size_id
color_id
price
Table sizes
id
name
Table colors
id
name
Models
class Product extends Eloquent {
public function size() {
return $this->hasOne('Size', 'id');
}
public function color() {
return $this->hasOne('Color', 'id');
}
}
class Size extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'size_id');
}
}
class Color extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'color_id');
}
}
This way I can easily echo the color/size of a product using {{ Product->size['name'] }}. Also, I want to pass Eloquent the size's foreign key size.id like Product::where('size_id', '5') rather than its name size.name.
Problem: Doing $products = Product::has('size', '=', '5')->get() does not give me any results, yet doing $products = Product::where('size_id', '5')->get() does.
I am pretty confused, what went wrong?
I think that the problem is that your ::has() method is looking for products with exactly 5 different sizes on each specific product, which would assume that you would be using $this->hasMany('Size') in your Product model. Where as the ::where() method is returning results where the size of the product is 5.
In the documentation they use an example of comments. A post will have a list of comments. You can find posts that have at least one comment (ie. Post::has('comments')->get()) or you can find posts that have more than 3 comments (ie. Post::has('comments', '>=', '3')->get()).
http://laravel.com/docs/eloquent#querying-relations