w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to eager load an association after eager loading on the parent?
I'm posting this an answer to make sure that it's clear it's been resolved. Once I'm capable I will accept this as the correct answer. Baldrick's comment got me to thinking about how exactly I was filtering out activities for the user so that I only had the activities logged to the active organization. I was performing: user.activities.where("organization_id = ?", org.id) Which would force a query every time regardless of what I've done. So I changed it to: user.activities.select { |o| o.id == org.id } Which now performs what I've wanted (after @Baldrick's recommendation as well).

Categories : Ruby On Rails

SDWebImage eager load images
If you look carefully at the -[SDWebImageManager downloadWithURL:options:progress:completed:] implementation, you'll find the lines: if (!url || !completedBlock || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { if (completedBlock) { // Complain about invalid URL, completely irrelevant to us at this point. ... } return operation; } So yes, it does nothing if completionBlock is nil. Why? Probably, the SDWebImage developers considered that method useless without that parameter passed. You'd better create a GitHub issue to ask them.

Categories : IOS

Eager load and store Singleton
Hm.. There is real problem, that user can create his AppDomains. There are no good way to get all loaded AppDomains in current process. I use bad hack founded in network: Hot to get list of all AppDomains inside current process?. Result code: public static void Main() { Console.WriteLine(Role.GetRole("Admin").Ololo); } public static class AppDomainExtensions { public static List<AppDomain> GetAllAppDomains() { List<AppDomain> appDomains = new List<AppDomain>(); IntPtr handle = IntPtr.Zero; ICorRuntimeHost host = (ICorRuntimeHost)(new CorRuntimeHost()); try { host.EnumDomains(out handle); while (true) { object domain; host.NextDomain(handle, out domain);

Categories : C#

Paginate Eager Load Constraints
When you call paginate() on your eager constraint it is configuring the query for you (setting the skip and take). The paginator that is generated will actually be discarded. Since you're just getting a single topic with its comments why not do this (same number of database calls)... $topic = Topic::find($id); $comments = $topic->comments()->order_by('created_at DESC')->paginate(10); Admittedly, you won't be able to use $topic->comments to get the paginator, and will have to use $comments instead, but that's not a terrible thing.

Categories : PHP

Eager Load lists() in Laravel 4
The reason it doesn't work is because when eager-loading it, using the with method, Laravel expects a relationship method to return a IlluminateDatabaseEloquentRelationsRelation object, so that it can call get on it. When you call lists, the query is already ran and what is returned instead is an array. What you could do, to reduce the data transferring, is use the select method on the query, and then run a lists on the categories Collection. Example: Model.php function categories() { return $this->belongsToMany('Category')->select('id'); } Whatever.php $posts = Post::with('Category')->get(); $categories = $posts->categories; // List only the ids $categoriesIds = $categories->lists('id');

Categories : PHP

Eloquent Eager Load Double Relationship
When setting up a relationship with a different foreign key you have to specify in the relationship which key you wanna use...return $this->hasOne('Author', 'foreign-key'); So if I understand your question you wanna setup a relationship to two authors, in the same author table.... So maybe something like this then?? (replace foreign_key with your table field) public function orig_author(){ return $this->hasOne('Author'); } public function second_author(){ return $this->hasOne('Author', 'foreign-key'); } public function dance(){ return $this->hasMany('Dance'); } Then just retrieve it like so...($id being the id of your dance) $dance = Dance::with('orig_author','second_author')->find($id); But to be honest, I've never tried having a double relationship with a table

Categories : Laravel

NHibernate - Map key returned as proxy, eager load?
IMO your problem isn't a lazy -> eager issue the issue it is more to do with how you are handling your session management. In most instances lazy loading is the best route to take. If your code is something like this:- using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { ... code to get a person transaction.Commit(); } } Then ALL data needs to be retrieved in the inner using block else if you attempt to get it outside you will get a Could not initialize proxy - no Session. This WILL throw the error you are seeing:- Person person using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { person = session.Get<Person>(1);

Categories : C#

Laravel/Eloquent - Eager Load using other than Primary Key
Yeah we can do eager loading on non-primary columns. For this you need to define db-data relationships in models:- Define your models Book & Author like this:- class Books extends Eloquent { public static $table = 'books'; public function bookauthors(){ return $this->has_many('authors','book_id'); } } class Authors extends Eloquent { public static $table = 'authors'; public function books() { return $this->belongs_to('books','book_id'); } } Now you can use following line of code to eager load books with authors on a key "book_id":- $books = Books::with(array('bookauthors'))->get(); I hope this helps you...i haven't tested on my local or test db. But had used similar eager loading for posts-tags relations

Categories : PHP

How to use eager load with constraints correctly in Laravel 4
I tried to do the same thing. I have companies and users tables. One company has many users. the code: Route::get('testeager', function() { $companies = Company::with(array('users' => function($query) { $query->where('email', 'like', '%koko%'); })) ->where('companies.id','=','54') // Put it here in order to debug easily. Take just one company ->get(); //$queries = DB::getQueryLog(); //dd($queries); return $companies; }); I added a new user with email like "koko@gmail.com" and commented and uncommented $query->where condition. And it worked for me. The only trouble I had that when I inserted the row in users table through phpMyAdmin the "deleted_at" field wasn't NULL so I couldn't get this user... It seems like something wrong somewhere e

Categories : Laravel

Eager load HTML/erb templates in Rails for AngularJS
For ERB templates you might use: <% Dir.glob(Rails.root.join('app','assets','templates', '*.erb')).each do |f| %> $templateCache.put("<%= File.basename(f).gsub(/.erb$/, '') %>", <%= ERB.new(File.read(f)).result.to_json %>); <% end %>

Categories : Javascript

laravel 4 eloquent eager load relation count
You should use the SQL Group By statement in order to make it works. You can rewrite your query like the following one. $beat = Post::with( array( 'user', 'likes' => function($q) { // The post_id foreign key is needed, // so Eloquent could rearrange the relationship between them $q->select( array(DB::raw("count(*) as like_count"), "post_id") ) ->groupBy("post_id") } )) ->where('id', $id) ->first(); The result of likes is a Collection object with one element. I'm assuming the relationship between model Post and Like is Post hasMany Like. So you can access the count like this. $beat->likes->first()->like_count; I'm not tested co

Categories : PHP

Laravel Eager Loading - Load only specific columns
Make use of the select() method: public function car() { return $this->hasOne('Car', 'id')->select(['owner_id', 'emailid', 'name']); } Note: Remember to add the columns assigned to the foreign key matching both tables. For instance, in my example, I assumed a Owner has a Car, meaning that the columns assigned to the foreign key would be something like owners.id = cars.owner_id, so I had to add owner_id to the list of selected columns;

Categories : PHP

Eager load associations with Active Model Serializers
One solution is to define your own weeks method on the TimecardSerializer. From there you can .includes() all the associations you want to eager load. class TimecardSerializer < ActiveModel::Serializer embed :ids, include: true has_many :weeks def weeks object.weeks.includes(days: [:sub_totals, :work_periods, :adjustments]) end end All the queries will still show up in the log but most will be a cached query instead of a real one.

Categories : Ruby On Rails

Fluent Nhibernate: Eager load private collections
I've only just briefly tested this and can't confirm it works 100% yet, but you should be able to use reflection to get the property and create an Expression that would eager load the property. First, get the property through reflection: var catsProperty = typeof(Man).GetProperty("Cats", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); Then, create an expression argument that points to a Man, and an Expression that gets the property: var expressionArgument = Expression.Parameter(typeof(Man), "m"); var propertyGetter = Expression.Lambda<Func<Man, IEnumerable<Cat>>>( Expression.Property(expressionArgument, catsProperty), expressionArgument); Then use that in your linq query: var man = session.Query<Man&g

Categories : C#

Filter parents by child attribute, but eager-load all children
If INNER JOIN is what you're looking for, I think Ship.includes(pirates: :parrots).where('parrots.name LIKE ?', '%polly%').joins(pirates: :parrots) gets it done.

Categories : Ruby On Rails

NHibernate - Eager load graphs of objects with multiple queries
I think there are several questions in one. I stopped trying to trick NHibernate too much. I wouldn't access entities from multiple threads, because they are usually not thread safe. At least when using lazy loading. Caching lazy entities is therefore something evil. I would avoid too many queries by the use of batch size, which is far the cleanest and easiest solution and in most cases "good enough". It's fully transparent to the business logic, which makes it so cool. I would: Consider not caching the entity at all. Use NH first level cache (say: always load it using session.Get()). Make use of lazy loading when only a small part of the data is used in a single transaction. Is there is a proven need to cache the data, consider to turn off lazy loading at all (by making the entities

Categories : C#

Can I configure an entity to eager load a relation using an EntityTypeConfiguration object?
There is no configuration for eager loading. You always have to call the Include method. For example in a helper method. return this.Employer.Include(e => e.EmployeeParams);

Categories : Entity Framework

Laravel: Eloquent, many to many relationship, how do I eager load only the id of related model?
$mdl = Business::with('industries')->find($business_id)->toArray(); $mdl['industries'] = array_pluck($mdl['industries'], 'id'); return $mdl; If you use this a lot, add the following method to your Business model: public static function getWithIdustryIds ($business_id) { $mdl = Business::with('industries')->find($business_id)->toArray(); $mdl['industries'] = array_pluck($mdl['industries'], 'id'); return $mdl; }

Categories : PHP

Can I use ActiveRecord::Associations::Preloader / eager loading to load a has_one relationship with dynamic conditions?
The problem is that self isn't your object in the has_many, it's the association proxy. If you want the profile object that is referenced in the association, it should be owner (though this is slightly dependent on the version of Rails you're running -- check the documentation for Rails association extensions for more details).

Categories : Ruby On Rails

Class Initialization in Form load with delegate
Make the Test method callable, not a constructor, like StartTest below. public void StartTest (Random zufall, ButtonAktivieren aktivierenCallback) { anzahlGezeigt++; if (anzahlGezeigt % 2 == 0) { aktivierenCallback(button, passiv); } if (anzahlGezeigt %2 > 0) { button = zufall.Next(1, 6); aktivierenCallback(button, passiv); } } public void Aktivieren(Random zufall, ButtonAktivieren aktivierenCallback) { passiv = true; StartTest(Random zufall, ButtonAktivieren aktivierenCallback); } Form code adjusts: Test Object; public Form1() { //some initializing code Object = new Test(); //the rest of initializing code }

Categories : C#

Delegate types and covariance with a generic delegate type
The problem is the two delegate types simply aren't compatible. In order to make this work you are going to need to add an indirection layer which converts the arguments between ICommand and TCommand. public void RegisterHandler<TCommand>(CommandHandler<TCommand> handler) where TCommand : ICommand { mCommandHandlers.Add( typeof(TCommand), (command) => handler((TCommand)command); ); }

Categories : C#

No overload for 'My Void' matches delegate 'My Delegate'?
It turned out that I should have been using a class besides string. I created a class inheriting from EventArgs to use to hold the string variable. This fixed the problem. It looked like: public partial class ClientChangedEventArgs : EventArgs { public ClientChangedEventArgs(string mewText) { this.NewText = newText; } public string NewText; } And in my User Control: public delegate void TextChangedVoid(ClientChangedEventArgs e) public event TextChangedVoid TextChanged;

Categories : C#

my own subclass's delegate methods wrapping around UITextField's delegate methods is crashing my app
It looks like you are trying some weird things when setting the delegate that are causing it to crash because you are trying to call methods on the wrong object. Most of the time when you call a method on a nil object, it just returns nil, but in cases such as this (I believe it is when the pointer thinks it is pointing to something, but it's actually pointing to the wrong type of object), it will give you the error that you are receiving. I would suggest that instead of doing it this way, you override your setter and getter of your delegate in your subclass to set the textField's delegate instead, such as: - (void)setDelegate:(id<UITextFieldDelegate>)delegate { self.textField.delegate = delegate; } - (id<UITextFieldDelegate>)delegate { return self.textField.delegate

Categories : Objective C

How to force eager loading in HQL
If you are getting the multiple bags exception, then it is because Hibernate cannot get all of your collections at once. You should pick a collection you wish to select with your base query and do so with a join, then use Hibernate.initialize to obtain the remainder of the collections you require. So it would look like this (I'm leaving off the select, since it isn't required): from Responsavel r join fetch pais p join fetch unidadeEmpresarial u join fetch representantes s where r.unidadeEmpresarial.id = :idUnidade You can experiment with which ones to include. What's left, requires initialization if you wish to detach from the Hibernate session to, for example, use the collections in the front-end or in a service class. Hibernate.initialize(listaResponsavelQualificacaoResponsavel);

Categories : Hibernate

How can I use eager loading in this case?
Updated I think, you should try this approach: @users = User.includes(:cars, profile: [:gender, :country, :prefecture]).confirmed.page(params[:page]).order('profiles.total_point DESC') Does it work?

Categories : Ruby On Rails

how to get eager loading in a many to many relationships?
I think you need this: var q = myContext.EntityC.Include("EntityA").Include("EntityB").ToList(); If you want Bs of an A: var aId; // = something...; var bs = from c in q where c.EntityAId == aId select c.EntityBId; And simply vice versa if you need As of a B: var bId; // = something...; var eas = from c in q where c.EntityBId == bId select c.EntityAId;

Categories : C#

Eager loading entities with raw SQL
You need to first attach the blogs to the context, and then explicitly load each property you need. As far as I know, this needs to be done individually, for example, inside a foreach. foreach (var blog in blogs) { context.Blogs.Attach(blog); context.Entry(blog).Collection(a => a.Comments).Load(); context.Entry(blog).Reference(a => a.Author).Load(); // Here you can use blog.Author and blog.Comments with no problem. }

Categories : C#

Can any one help me how to do eager loading with scope
You have to define a custom association instead of the scope and use this for eager loading: has_many :more_no_comments, :class_name => 'Comment', -> { where "no_times > 10" } and then User.includes(:more_no_comments).all.collect{|u| u.comments.more_no_comments} See this question.

Categories : Ruby On Rails

.NET ORMLite and Eager Loading
Lightweight orms don't contain features available in EF or nHibernate, there are fast but you must write more code. Eager loading doesn’t exist in ormlite. But let’s start from beginning:) Your account class should looks like following: public class Account { public string Id { get; set; } public string CreatedById { get; set; } [References(typeof(User))] public int CreatedBy { get; set; } } public class User { public string Id { get; set; } public string Name { get; set; } } You can't have property CreatedBy of User type - service stack ormlite doesn’t support this. Your class must looks like your table and in table you have int column of the name CreatedBy;) Here you can read how to make join from ormlite- JoinSqlBuilder

Categories : Dotnet

Is this eager loading doing what I think it's meant to be doing?
The eager loading looks like it should work, but much more importantly these are things that you could and should be doing using SQL. Loading and iterating through all the ActiveRecord models in your DB has the potential to be incredibly time consuming (as you've found), whereas working out how to do it in SQL will allow you to load all the models directly from a single query. It can take a while to get a handle on this, but it's well worth it!

Categories : Ruby On Rails

Hibernate Default Lob Lazy/Eager
Yes it is loaded lazily. Read this jira ticket and comment for this by Emmanuel Bernard. And also this question

Categories : Hibernate

hibernate One-to-many association : subselect or eager
I think you meant by default eager instead of lazy in the first line of the question. POINT TO REMEMBER When associations are included in criteria query, they are by default eagerly fetched. In your case you do not need the mapping books lazy:false in Author. In terms of optimization I would vouch for the below approach: class Author { String name static hasMany = [books: Book] static mapping = { //books lazy:false (DO NOT NEED) } } class Book { String bookName //set belongsTo if you need bi-directional one-many //books gets cascade deleted when author is deleted //static belongsTo = [author: Author] } //Bootstrap def author1 = new Author(name: "Dan Brown") def book1 = new Book(bookName: "Da Vinci Code") def book2 = new Book(bookName: "Angels A

Categories : Hibernate

Again: EF 5 code first eager vs. lazy loading
As far as I know you can't prevent that (what is called "relationship fixup"). But why do you want to prevent it? Your understanding is correct: "...attaches automatically the already loaded product(s) to the category...". Here "already loaded" includes results from earlier (tracked) queries with the same context and the result of the current query. There is no implication for the query that is run. The query does what you specified: Load products including categories (single JOIN in the DB). The query does not have an additional JOIN that links those categories to all related products. Relationship fixup only happens in memory with attached objects and therefore doesn't cause unnecessary query overhead. This behaviour is the same for eager and lazy loading.

Categories : Entity Framework

Ignore a FetchType.EAGER in a relationship
Never actually tried this but might worth a shot... Assuming that the session factory is available at the DAO layer via injection or any other means you can implement something similar in a (probably new) DAO method: List<Person> result = (List<Person>) sessionFactory.getCurrentSession() .createCriteria(Person.class) .setFetchMode("address", FetchMode.LAZY) .list(); return result;

Categories : Java

Why Hibernate Eager Fetch Does Not Work?
How can you have a @OneToMany when you don't have ParentId in child table? You are missing a key to have a multiple children related to single parent; add ParentId to table Child and use that column in @JoinColumn(name = "ParentId") EDIT: Init Parent.child with private List<Child> child = new ArrayList<Child>(); Change private Integer pid; with private Parent pid; (and add to @OneToMane mappedBy="parent") Try Annotate field and not setter Make your Parent.setChild() just an assignment That are - usually - the best pratice for a parent-child relationship

Categories : Hibernate

Rails Eager loading explanation
The result of your query eager loads the posts as the result of the Person#posts method. I'm not quite clear on the format of the output you are expecting. If you simply want two arrays, one of people and one of all posts by those people you can split it into two queries. @people = Person.where(...) @posts = Post.where(person_id: @people) This is the same query done by eager loading, but it will return posts in their own array.

Categories : Ruby On Rails

Laravel 4 Eager Loading in Many to Many Relationship
You should try: $facilities = Facility::with('photos')->get(); Remember, the argument you are passing to with() is the method, not the model, so if you have another method in the model, say: location(), you'll call: $facilities = Facility::with(['photos', 'location'])->get();

Categories : PHP

NHibernate - Nested Eager loading is being ignored
It should work with something like this: QueryOver<Parent>() .Where(c => c.Id == id) .Inner.JoinQueryOver(p => p.Children) .Inner.JoinQueryOver(c => c.GrandChild) .Inner.JoinQueryOver(g => g.GreatGrandChildren) .Fetch(p => p.Children).Eager .Fetch(p => p.Children.GrandChild).Eager .Fetch(p => p.Children.GrandChild.GreatGrandChildren).Eager .TransformUsing(Transformers.DistinctRootEntity) Fetch.Eager tells NH to load those nested collection within one request, TransformUsing basically tells it you want a distinct on Parent

Categories : C#

How to retrieve values using FetchType.Eager?
Inspired by this and link User user = (User) session.createCriteria(User.class) .setFetchMode("permissions", FetchMode.JOIN) .add( Restrictions.idEq(userId) ) .uniqueResult();

Categories : Java

Complex :includes for Eager Loading
Sounds like you need to add some conditions to an association: has_many :messages, -> { select('messages.*, message_tags.status as read')) } and then something like: Conversation.joins(:phones) .where('phones.id' => 2) .order('last_message_at DESC') .includes(:messages => :message_tags) .where(:message_tags => { :user_id => current_user.id })

Categories : Ruby On Rails



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.