I have two tables, tracks and echonestrecords. Tracks have one record in the echonestrecords table with information about the track.
tracks has these columns:
id, title, artist, created_at, updated_at
echonestrecords has these columns:
id, track_id, tempo, mode, key
The track object has the hasOne()-function to return the echonestrecord.
The echonestrecord object has the belongsTo()-function to return the track.
I want to make an Eloquent-query to get all tracks which have an empty row in the echonestrecords-table. That is, a row there the tempo is null.
I can do it like this with the raw query, which doesn't return Track objects.
$tracks = DB::table('tracks')
->select('tracks.*')
->join('echonestrecords','echonestrecords.track_id','=','tracks.id')
->where('echonestrecords.tempo',null,'NULL')
->get();
But I can't figure out how to do this with Eloquent. I figured it must be something like:
$tracks = (array('echonestrecord' => function($query) {
$query->where('tempo', null, 'NULL');
}))->get();
But this returns all tracks! I'm confused.
Can you help me?
I solved it. Yahooo..
The answer was using whereHas:
$tracks = Track::whereHas('EchoNestRecord', function($q)
{
$q->whereNull('tempo');
})->paginate(3);
What you probably need is to create a relation and filter it a little bit more:
class EchoNestRecord extends Eloquent {
protected $table = 'echonestrecords';
}
class Track extends Eloquent {
protected $table = 'tracks';
public function RecordsWithNoTempo()
{
return $this->hasOne('EchoNestRecord')->whereNull('tempo');
}
}
Then you should be able to:
$track = Track::find(1);
foreach($track->recordsWithNoTempo as $record)
{
echo $record->name;
}
Use
dd(DB::getQueryLog());
To check the generated query.
Related
Laravel Version: 5.6.39
PHP Version: 7.1.19
Database Driver & Version: mysql 5.6.43
Description:
When I chain where and orWhere in a model accessor to count related model , I get wrong result and here is my query. the count is returned strange result without filtering by the calling event id,
class Event extends Model
{
protected $table = 'events';
public function registrations()
{
return $this->hasMany('App\Components\Event\Models\Registration','event_id','id');
}
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where('reg_status','=','Confirmed')
->orWhere('reg_status','=','Reserved')
->count();
}
}
Steps To Reproduce:
the following queries return me the expected results, however In my knowledge the first query should return the same result if i am not wrong, so i think this is a potential bug.
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->whereIn('reg_status', ['Confirmed', 'Reserved'])
->count();
}
}
class Event extends Model
{
public function getSeatsBookedAttribute()
{
return $this->registrations()
->where(function($query){
$query->where('reg_status','Confirmed')
->orWhere('reg_status','Reserved');
})
->count();
}
}
and here is the query dump,
here is the query when I donot explicit group it.
"select count(*) as aggregate from events_registration where (events_registration.event_id = ? and events_registration.event_id is not null and reg_status = ? or reg_status = ?) and events_registration.deleted_at is null "
and here is the query when i group it explicitly,
select count(*) as aggregate from events_registration where events_registration.event_id = ? and events_registration.event_id is not null and (reg_status = ? or reg_status = ?) and events_registration.deleted_at is null
The reason this happens is because you're chaining where() and orWhere(). What you don't see behind the scenes is a where event_id = :event_id applying to your query. You end up with a query that looks something like this:
select * from registrations where event_id = :event_id and reg_status = 'Confirmed' or reg_status = 'Reserved'
In normal SQL you'd want to put the last 2 conditions in parentheses. For Eloquent, you'd need to do something like this:
return $this->registrations()->where(function ($query) {
$query->where('reg_status', 'Confirmed')
->orWhere('reg_status', 'Reserved');
});
You can chain the toSql() method on these chains to see the difference. Note, that in this case, I believe whereIn() is the semantically correct thing to do.
Eloquent can handle this for you, though; scroll down to "Counting Related Models" in the Querying Relations part of the Eloquent Relationships docs:
$posts = App\Event::withCount([
'registrations as seats_booked_count' => function ($query) {
$query->where('reg_status','Confirmed')
->orWhere('reg_status','Reserved');
}
])->get();
We have two Models:
SimpleModel (id, country, code)
ComplexRelatedModel (id, name, address)
SimpleModel has many ComplexRelatedModel, then
class Product extends Model
{
protected $fillable = [
'name'
];
/* hasOne */
public function complexRelatedChild()
{
return $this->hasOne(self::class, 'parent_id', 'id');
}
}
If we do
$simples = SimpleModel
->with('complexRelatedChild')
->simplePaginate(100000 /* a lot! */);
And we need only do
foreach ($simples as $simple) {
echo $simple->complexRelatedChild->name;
}
Any ComplexChild has hydratated and ready. This takes a lot of memory in my case. And we need just one field without any funciton or feature of Model.
It's possible use some data field from related object or with eloquent this isn't possible?
Not sure I completely understand your question. You want to only load one field from the complexRelatedChild relation to keep memory limit down?
You could do:
$simples = SimpleModel::with(['complexRelatedChild' => function($query){
return $query->select(['id', 'name']);
})
->simplePaginate(100000);
Which can be simplified to:
$simples = SimpleModel::with('complexRelatedChild:id,name')
->simplePaginate(100000);
However if I were you, I would try to paginate less items than 100000.
Update:
You could use chunk or cursor functions to process small batches of SimpleModel and keep memory limit down.
SimpleModel::chunk(200, function ($simples) {
foreach ($simples as $simple) {
}
});
or
foreach (SimpleModel::cursor() as $simple) {
}
See the documentation for more information
I'm building a small application where I'm having many to many relationship between two models something like this:
class Contact extends Model
{
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact', 'company_id', 'contact_id')->withTimestamps();
}
}
Now while retrieving this I want only the latest model through the pivot table or you may say relational table, for this I'm trying to implement:
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->latest()->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
But I'm unable to retrieve the latest table it is showing the same old value or the first value.
Guide me how can I achieve this.
You can try this :
latest() is a function defined in Illuminate\Database\Query\Builder Class.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
So, It will just orderBy with the column you provide in descending order with the default column will be created_at
OR
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->orderBy('created_at', 'desc')->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
So basically idea is if you are finding the relational data from many to many relation like $data->company() in this question and try to sort this with latest it will sort the company table with created_at sorting desc in order to get relational latest data you need to sort through pivot tables i.e.
$getCompany = $data->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first();
This is how I achieved the latest relational table.
Note: You must have pivot table in your relation, in this answer created_at is the pivot field I'm using.
I am new with Laravel, I was able to query Many-to-Many relationships. Where 'template_dynamic' is the pivot of two tables 'template' and 'dynamic'.
// Template Model
class Template extends Eloquent
{
protected $table = 'template';
protected $guarded = array('template_id');
protected $primaryKey = 'template_id';
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->select('*')
->withPivot('template_dynamic_id')
->orderBy('template_dynamic_html_sort', 'ASC');
}
here I was able to retrieve the records
// Template Controller
$dynamic_fields = Template::find($rec->template_id)->dynamic;
what I want to do now is that pivot table has-many properties 'template_dynamic_option'. How will I query the records and combine it with $dynamic_fields variable?
// What I want to do is something like this. But sadly this is an invalid syntax
$dynamic_fields = $dynamic_fields->with('template_dynamic_option');
Any recommendation or enhancements are welcome.
Thank you in advance.
First, I am pretty sure you don't need the select('*') in your relationship query there.
But let's get to your actual problem ;)
To access the pivot table in Eloquent is pretty simple.
$dynamic_fields = Template::find($rec->template_id)->dynamic;
foreach($dynamic_fields as $dynamic){
var_dump($dynamic->pivot)
}
The thing is though, by default only the keys of the pivot table are present in the object.
To change that you have to define them with withPivot(). Actually like you already did but not with the id.
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->withPivot('template_dynamic_option')
->orderBy('template_dynamic_html_sort', 'ASC');
}
And if you have multiple additional columns use this syntax:
->withPivot('template_dynamic_option', 'foo', 'bar');
Let's say I have the following model:
class Movie extends Eloquent
{
public function director()
{
return $this->belongsTo('Director');
}
}
Now I'd like fetch movies using a where condition that's based on a column from the directors table.
Is there a way to achieve this? Couldn't find any documentation on conditions based on a belongs to relationship.
You may try this (Check Querying Relations on Laravel website):
$movies = Movie::whereHas('director', function($q) {
$q->where('name', 'great');
})->get();
Also if you reverse the query like:
$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();
// Access the movies collection
$movies = $directorsWithMovies->movies;
For this you need to declare a hasmany relationship in your Director model:
public function movies()
{
return $this->hasMany('Movie');
}
If you want to pass a variable into function($q) { //$variable } then
function($q) use ($variable) { //$variable }
whereBelongsTo()
For new versions of Laravel you can use whereBelongsTo().
It will look something like this:
$director = Director::find(1);
$movies = Movie::whereBelongsTo($director);
More in the docs.
is()
For one-to-one relations is() can be used.
$director = Director::find(1);
$movie = Movie::find(1);
$movie->director()->is($director);