yii relation HAS_MANY add condition - php

I write this line at my controller
<i>
$model_town=ResTown::model()->with(array('get_by_town'))->findAll(array('limit'=>'3'));
</i>
I need to make get_by_town with limit=3 and user_active=1
I got all records but conditions don't work

If you would like to add condition on related table you should write it inside with() method.
So, you should get something similar `
->with('get_by_town'=>array('limit'=>3, 'user_active'=>1))
But in some cases it can not helps you, because it depends on many things: for example, relation type, join type and so on.
The easiest way to work with ActiveRecord for me, first of all write down pure sql, and then convert to ActiveRecord representation. Thus, I get optimized query and exactly knowing of what I'm doing %)

Related

Automatically add where clause to every queries on a model

Currently I am to do Model::where('status', 1) to filter off inactive models before adding any other subqueries to it. I find myself doing this all the time and Its quite stressful as sometimes I could forget to add that part. I wish to have something that will automatically add the where clause anytime I run a query on the model. Something that works like the typical Laravel SoftDeletes that adds the WHERE deleted_at IS NULL clause automatically to all queries.
Example:
Instead of writing Model::where('status', 1)->first(), I could just write Model::first() and this will be automatically transformed to Model::where('status', 1)->first().
How do I achieve this please ?
What you're looking are the
Query Scopes

Laravel Eloquent: get unique models between relationships

I have a scenario like this:
I have User model that has an OneToMany relationships with the Post model.
I have a Hashtag model that has an OneToMany relationships with the Post model.
Recap: ONE user has MANY posts, ONE post belongs to ONE hashtag, ONE hashtag has MANY posts.
I would like to fetch only unique users records of an hashtag.
I'm able to do it in non scalable way (fetching all the posts first and then iterate filtering by user id), but I need to maintain scalability for large record numbers.
Edit: I saw a partial solution in Laravel docs.
Laravel eloquent has a method called unique().
With that method I can specify the parameter which should be unique in query.
In my case figured it out with:
$users = $hashtag->posts->unique('user_id');
But I can't paginate query in this way...
Has anyone a solution for that?
You have to paginate your main model caller.
I don't know exactly if this is can reproduce your actual scenario, but let's see this example:
Let's say you have the model hashtags
So let's say the code could be something like this:
$users = DB::table('hashtags AS tags')
->select('tags.*')
->join('[posts AS post','post.id','=','tags.id')
->distinct()
->paginate(5, ['tags.*']);
I don't know if your query it'll be very accurate, but for this, I believe the best approach it'll be you do a raw query, could look like it'll be costly to your database and the operation, but you can work around this approach indexing and partitioning your database.
Remembering always the eloquent sometimes even when we're building join queries could be more even costly to your database.
Since you're worried about scalability so the best thing could be for too could write a view to fetch all the data with proper indexing and partitioning.
Try to use DISTINCT
$users = $hashtag->posts()->selectRaw('DISTINCT(user_id) AS unique_user_id')->paginate(10);
OR
use groupBy()
$users = $hashtag->posts()->groupBy('name')->select('user_id')->paginate(10);

is it advisable to use polymorphic relations with joins?

I've created migrations and also their relationships. looks like I'm using polymorphic relations, because in one table, I could have the value of one model or i could have the value of another model. as you might guess, I have something like this
ID Mappable_type Mappable_id value
Mappable_type could be one or many other models. mappable_id will be appropriate id from that model. I needed this because I'm creating dynamic form builder and that's how I designed a database.
Now I need to fetch some records from 5 tables together, so I gotta use joins. the table where I have mappable_type is at the third place from those 5 joins. now What should I do also to only fetch data from these 5 joins that have specific model type that is in that morph table? I'm doing something like that for now:
$final = Dynamic::join('dynamic_properties_values','dynamic_properties_values.dynamic_id','=','dynamic.id')
->join('dynamic_properties_mapping','dynamic_properties_mapping.id','=','dynamic_properties_values.mapping_id')
->where('dynamic_properties_mapping.mappable_type','=','App\Driver')
->get();
As you see, I have written by hand something like
"App\Driver"
. It doesn't matter I have written it by hand or had it saved into a variable and than used it here. WHat really bothers me is that let's say when I was inserting data into these morph tables, Model got saved as "App\Driver". what if I make a mistake and when fetching with joins, I write something like App\Http\Driver? or what If I changed the location of the model itself in my code project?
What's the best practice not to make those kind of errors by the time my project reaches huge amount of users?

Use a join statement and save the results as a relation like "with" does? - Laravel 5.2

I'm trying to get data from multiple relationships. But I don't want to end up with multiple queries. So the with method won't work for me.
I want to use joins to get the data needed, but laravel overwrites keys if they are duplicated. Is there a way to save the results from a join as a relation. Something like this below (join is incorrect I know).
Post::select('post.*', 'category.*')->join('category');
If both have an 'id' field it's overwritten by the other. So I would like to have category.* results as a relation so I can call ->category->id like I can when I use the with method.
Is there any way to do this?
You may use the whereHas and orWhereHas methods
Check this link:
http://laravel.io/forum/04-19-2014-many-to-many-to-many-in-wherehas
And Laravel Documentation:
https://laravel.com/docs/5.1/eloquent-relationships

PHP & MySQL Tickers..Is this standard practice?

I currently have about 4 different database tables which output to html tables. Each of these tables uses a count query to calculate data from a 5th table.
That's no problem, but what about when I want to sort and order the data, and paginate etc (like with zend). If it were a one page table, I could probably sort an array.
My thought was, to use a ticker. But that would require a new column in all 4 tables and seems like overkill or like there could be a better way.
Sadly, I can't find much info on it (likely because I don't know what to search for).
Advice?
..and please take it easy, I'm new and learning.
Assuming youre using Zend_Db_Table_Row and that you dont need to persist any modifications you might make to these rowsets then you can just append the virtual columns to the row object and have them be accessible via array notation. So if youre doing it all in one query now just use that same query, and the column should be there.
OTOH, if youre using a Data Mapper pattern then simply adjust your hydration to look for this "virtual column" and hydrate it if it exists in the result data. Then in your getter for this property have it see if the property is null or some other negative specification, and if it is, to execute a calculation query on that single object or return the already calculated result.

Categories