Get all child categories in relationships laravel 5 - laravel-5.1

There is a table id|title|pid.
How to get all of the child categories "recursive" using relationships in Laravel 5.1.
Created child relations
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function child() {
return $this->hasMany(self::class, 'pid', 'id');
}
Now you need to run recursively and get all of the child categories in all categories.
Thanks.

It sounds like what you're talking about is something called Nested Sets.
https://github.com/etrepat/baum is a pretty decent package for this sort of thing.
Hope this helps!

Related

How to make a "deep" transformation in Grails withCriteria contains projection?

I am using Grails 2.2.4 to build a web application, and now I am having a complex problem with Grails withCriteria operation. I have 3 classes as below:
class Person {
int id
String name
Set<Car> cars = [] // One-to-many relationship
Company currentCompany // One-to-one relationship
}
class Car {
int id
String manufacturer
String brand
double price
Person owner
}
class Company {
int id
String name
Set<Person> employees = []
}
And now I want to query data from Person as root class along with associated data like this:
List result = Person.withCriteria {
projections {
property('id')
property('name')
createAlias('cars', 'c', CriteriaSpecification.LEFT_JOIN)
property('c.brand')
createAlias('currentCompany', 'com', CriteriaSpecification.LEFT_JOIN)
property('com.name')
}
lt('id', 10L)
resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
}
And the problem is, I don't know how to transform deeply the result data to a List of persons to make sure every single element contains its data as the class structure. I tried many methods like
resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
resultTransformer(CriteriaSpecification.aliasToBean(Person.class))
but nothing worked as I expected.
Does Grails 2.2.4 support this? If yes so what is the correct syntax?
Thank you so much.
Actually, after researching many articles, Grails documentation and even its source code, I think the best way to do this is implementing a custom transformer for my own purpose. The most difficult thing here is how to transform data to association objects and gather them to collection inside the root entity. And I have created one here:
http://www.mycodestock.com/code/10333/
Hope it helps you guys who may need something like mine.

TYPO3 Flow Dependency Injection and geting objects that are sub objects of others

Hello I have been learning to use FLOW and have some questions:
I have an action in a controller like this:
/**
* Displays a subproduct.
*
* #param \My\Package\Domain\Model\Product $product The main product.
* #param \My\Package\Domain\Model\Subproduct $subProduct A sub-product of $product.
* #return void
*/
public function subproductAction(\My\Package\Domain\Model\Product $product, \My\Package\Domain\Model\Subproduct $subProduct) {
$this->view->assign('product', $product);
$this->view->assign('subProduct', $subProduct);
}
This was fine for testing and learning about the framework, but now I want to make sure that $subProduct is actually a sub-product of $product.
What would be the best way of doing this?
Use DI (like it now is) to get both the product and subproduct and check if $product
contains $subProduct, if not alter what variables I assign to my
view? Or:
Inject the product and use to some method of $product to
return the $subproduct, if it is a sub-product of product.
Create a repo function that gets the subproduct if it's product
column is the product?
Products can contain hundreads of subproducts and for my application I only need to get one subproduct and display that, so I can't just use my products getSubProducts() method as this would return all of them.
Thanks for any tips
I know it is old question, but there is nothing about dependency injection.
In your \My\Package\Domain\Model\Product you should have field protected $subProducts of type \Doctrine\Common\Collections\Collection<My\Package\Domain\Model\Subproduct> with setsubProducts, getSubProducts and maybe addSubProduct (get + add) methods inside.
It is collection so you can use contains, add and so on.
Now when you have product assigned to view in your controller - in fluid sth like {product} - you can use fluid for view helper on {product.subProducts} - there is no need to get it in controller (all get [and some other] public methods from Model works that way).
Just for validation (on update) you can check if $product->getSubProducts->contains($subProduct) then something..
I would go with the first approach. Let the framework give you the entities and check in your action if the $subProduct actually belongs to the $product.
From my experience it's often the best to go with the simple approach.
I'm not sure what you are trying to achieve here but if you only want to display the $subProduct why no DI the $subProduct and use it's relation to the product in the template? I mean the $subProduct has to have some inverse relation to the product right?
So, your action would look like this:
/**
* Displays a subproduct.
*
* #param \My\Package\Domain\Model\Subproduct $subProduct A sub-product of $product.
* #return void
*/
public function subproductAction(\My\Package\Domain\Model\Subproduct $subProduct) {
$this->view->assign('subProduct', $subProduct);
}
and in your template you could do something like:
{subProduct.product.title}
I hope this helps. To give a decent advice it would be necessary to know you whole application or at least one needs a besser understanding of the problem.

Creating custom model using other models in ASP.NET MVC

As the title suggests I have two models Products And Orders which are actually two table in my database and I have used a LINQ to SQL class to create there models. Now I wan to create a model named "OrderDetails" which will have properties from both the model like product name and id from product and Order number from orders something like this. An then I want to create a view from this custom model and from which I want to add "CRUD" operation. What should be my approach. And in many scenarios I may have to use data from more than 4 models. Please help. I'm wondering helplessly and I have only two days experience in ASP.NET MVC.
I'd go this route:
namespace Models
{
public class OrderDetails
{
private Products _products;
private Order _order;
public OrderDetails(Order order, Products products)
{
_order = order;
_products = products;
}
// now expose whatever fields or logic you need.
// for instance:
public Customer OrderCustomer()
{
return order.Customer();
}
}
}
However, before you go around making all of these new models, are you sure you need them? Can you simply use two instances, either passed around separately or in a Tuple? You can get some useful abstraction here, but if you don't need it, keep it simple.
Linq to SQL does not support custom mapping to the extent that you're looking to do. What you'll want to look at is a full ORM. I highly recommend nHibernate, but Entity Framework, if you must, will do what you want.

How can I do an eager load when I don't know the name of the property I want to load?

I have a generic repository and when I'm using a DoQuery method to select objects from the database, I need to load some of the related entities in order to not get nulls in the place of the fields that are foreign keys.
The problem is that the repository is generic, so I do not know how many properties need loading or what their names are (unless there's some way of getting them) how can I make it so that all of the foreign keys have their entities loaded while still keeping this repository generic?
Here's the DoQuery method:
public ObjectQuery<E> DoQuery(ISpecification<E> where)
{
ObjectQuery<E> query = (ObjectQuery<E>)_ctx.CreateQuery<E>("[" + typeof(E).Name + "]").Where(where.EvalPredicate);
return query;
}
And a link to the original code for the entire repository.
I posted this once before and never got the answer to it but I figure this one is a little bit more relevant since before people were assuming I knew the property names and could do:
.Include("PropertyNameIKnowNeedsToBeLoaded")
Here's the question I posted before hopefully that will provide a little information on where I'm at with this.
Any help is appreciated.
Thanks,
Matt
You'll have to invert the control by passing into the method the depth that should be fetched to. I'm not familiar enough with the Entity framework with exactly how to do that. You could pass in an integer representing the fetch depth, and the method can figure out how to construct a query with the related entities to that depth.
I have solved this problem by the next way:
public IQueryable<E> GetAll()
{
Type et=typeof(E);
ObjectQuery<E> oq=_context.CreateQuery<E>("[" + typeof(E).Name + "Set]");
foreach(System.Reflection.PropertyInfo pi in et.GetProperties())
{
if (pi.PropertyType.Name.Contains("EntityCollection"))
oq=oq.Include(pi.Name);
}
return oq.AsQueryable();
}
but it steel has a problems with dipper relations. So steel thinking about this problem
You can get the relations ends names for a type and call Include for all relations.
public ObjectQuery<E> DoQuery<E>(ISpecification<E> where) where E : new()
{
ObjectQuery<E> query = (ObjectQuery<E>)_ctx.CreateQuery<E>("[" + typeof(E).Name + "]").Where(where.EvalPredicate);
IEntityWithRelationships entityWithRelationship = (IEntityWithRelationships)(new E());
IEnumerable<IRelatedEnd> relatedEnds = entityWithRelationship.RelationshipManager.GetAllRelatedEnds();
foreach (IRelatedEnd end in relatedEnds)
{
query= query.Include(end.TargetRoleName);
}
return query;
}
I added a "new" generic constraint because I need to get an IEntityWithRelationships from the queried type. I hope this helps.

MVC Partial Views, Models and more

I am pretty new to ASP.NET MVC and I am trying to get my head around some of the design concepts at the moment. One thing I am currently stuck on is how (best) to handle a situation such as that described below.
Suppose I have a page that needs to render a number of "sections". For example, on the left hand side there is a list that is data driven and then the selected item in the list displays a further list in another section on the page. For better understanding lets suggest the left hand list is a list of movie categories and the other list displays a list of movies that are contained within that category, along with the various movie details.
Now, I have some form of ORM such as Entity Framework, LINQ to SQL or whatever that maps the tblCategory and tblMovie database tables into Category and Movie entities respectively. These entities live in the MyMVCApp.Data.Entities namespace. I then use a repository pattern located in the MyMVCApp.Data namespace to encapsulate the queries (via LINQ) against these entities to return our model entities.
This is where my first question lies. Should the repository be returning view model entities or domain entities which are then extended to produce view model entities? In my naive mind I see the entities returned from the ORM as simply containers for the data with domain entities containing the business logic. So surely there should be an abstration here?
Anyway, back to my scenario. Now lets assume I wish to present the two sections described at the beginning of this. I am assuming that what should be happening here is my domain entity model would contain a list of categories and their associated movies. So something like a List each of which contains a List.
This model would have been populated somewhere. This is my second question. Say my assumption above is correct and it is simply data entities are returned from the ORM. Now I have a namespace/project called MyMVCApp.Core.Model (or the like) with some domain entities such as the Movie and Category entities mentioned in the previous paragraph. Do these entities have methods on them to retrieve the data from the ORM and populate themselves? Or does the repository retrieve these populated entity models? And another question on this part, if I have a Movie and Customer entity in my ORM is it acceptable to be having domain entities named the same?
Finally, I assume the controller now has this populated list of Category and Movie objects and passes it back to the view. I am guessing it is best to have each of the sections described at the beginning as partial views and passing the populated model to each? So, it may be the IndexController which retrieves the populated CategoryMovies entity, passing this to the Categories partial view and the Movies partial view. I would then need to somehow determine the selected Category (quesrystring?) and display the appropriate list of Movies in that category within the view.
OK, so if anyone has got to this point in my ramblings I will take a deep bow. I hope I have explained my mixed up thoughts and questions in sufficient detail for someone to provide some kind of enlightenment.
Thanks for listening! :-)
Since you didn't mention it, I will assume you are new to DDD concepts. DDD compliments the "M" in MVC by placing logic where it belongs. And, I think a good amount could be applied here.
In strict DDD form, I would use your Movie example as an Aggregate Root (a DDD concept). Within Movie, you would have business logic (methods) that obtain the categories and related entities directly related to Movie (i.e. Categories-this-movie-belongs-in). This assumes the "category" list you want to display is a list of categories this movie is in.
public class Movie
{
private IList<Category> _categories;
public IList<Category> FetchCategories()
{
// you can lazy-load here, use Linq-to-Sql, etc.
return _categories;
}
public void AddCategory(Category c)
{
_categories.Add(c);
}
}
Of course, you can treat Categories as a Value Object (VO, a DDD concept) here if you don't have an identity on them.
Now, what gets more interesting is if you do want to keep an identity on your Categories, treating them as Aggregate Roots with multiple entities and relations to other VOs and alike. In this case, you would want to utilize the DDD concept of Services to combine the two aggregates into your requested Model you want to pass to your Controller. This allows you to create business rules around loading the categories.
public class Movie
{...}
public class Category
{...}
public class MovieCategory : Movie
{
private IList<Category> _categories;
public IList<Category> Categories
{
get
{
return _categories;
}
internal set
{
_categories = value;
}
}
}
public class MovieCategoryService
{
public MovieCategory FetchMovieCategoryByMovieId(int id)
{
MovieCategory mc = _movieRepository.FetchMovie(id);
// do some logic here, some checks, etc
// to obtain your Categories list. Maybe querystring?
IList<Category> cats = ...;
mc.Categories = cats;
return mc;
}
}
The concept is that you now have logic in the domain layer, in this MovieCategoryService, to handle the complex creation of these relationships, or using Factories to create complex types as well.
This gives you a model you can pass around to different View and PartialViews.
The final step in your original post is how to get this into the View. I've been playing with the ViewModel approach to this issue. Creating ViewModels either dynamically, or as a class, and hanging all of the entities on this ViewModel. A recent StackOverflow question hits on this concept. ViewModel Best Practices
I've passed the Model directly into Views, and I am now trying this approach. It does clean things up, as your DOmain Model really should be disconnected from the "logic" on your page. I find myself thinking, "Dang it. I need to get this partialview populated based on this ID. Guess that means another method on the entity." Going the ViewModel approach removes the logic/thinking from the Domain Model, and puts it where it belong - in the Application/UI layer of where you are fine-tuning your view/partialview.
First of all, I think you should just get started with a simple project and try the various scenarios out you pictured in your long question :). There is nothing written in stone, you can use whatever architecture with datalayers and services or whatever, you like !
Or does the repository retrieve these populated entity models?
I would say yes. Your controller graps these from the service and gets them, populated and all and just moves them to the view in order to be displayed.
I am guessing it is best to have each of the sections described at the beginning as partial views and passing the populated model to each?
And again i think you're on the right track ;).
It is a nice idea to give a view model entity to the view instead of the whole domain entity itself thereby providing the view only the required stuffs to work on
First of all return a List of Categories from your Domain, then construct a Movie view which takes the category name as a parameter something like this
- <Host>/Movies/Comedy
- <Host>/Movies/Horror
which would in turn display the movies which belongs to that particular category

Resources