Subrelationships not using previous conditions - laravel

I'm using Laravel 4. I have the following models:
class User extends Eloquent {
protected $table = 'users';
public function questions()
{
return $this->hasMany('UserQuestion', 'user_id', 'user_id');
}
}
class UserQuestion extends Eloquent {
protected $table = 'user_questions';
public function user()
{
return $this->belongsTo('User', 'user_id', 'user_id');
}
public function subquestions()
{
return $this->hasMany('UserSubquestion', 'question_id', 'id');
}
}
class UserSubquestion extends Eloquent {
protected $table = 'user_subquestions';
public function question()
{
return $this->belongsTo('UserQuestion', 'question_id');
}
public function answers()
{
return $this->hasMany('UserAnswer', 'subquestion_id', 'id');
}
}
class UserAnswer extends Eloquent {
protected $table = 'user_answers';
public function subquestion()
{
return $this->belongsTo('UserSubquestion', 'subquestion_id');
}
}
I have the following query:
$results = User::with(['questions' => function($query) {
$query->where('status', '1');
$query->where('category', 'medicine');
}])
->with('questions.subquestions', 'questions.subquestions.answers')
->get();
However, the where conditions I'm applying to the questions relationship aren't being applied to the joined tables (subquestions and answers).
How can I make the conditions apply to them as well?
Note: The values of status and category in the conditions are dynamic (i.e. won't always be 1 or medicine).

Try doing your call like this instead:
$results = User::with(['questions' => function($query) {
$query->where('status', '1');
$query->where('category', 'medicine');
},
'questions.subquestions',
'questions.subquestions.answers'
])->get();
Note, this time the method with is only called once.

Related

Laravel eloquent multiple levels of relations

Alright so I am basically trying to retrieve all animal_registry codes based on a user ID.
Idea is that
1 user has many jobs.
Jobs are consisted of many "Jobs data".
Jobs data has many "Animal registry" entries.
These are my relations
Image relations link (click)
And these are my relations in Laravel
class User
{
public function jobs()
{
return $this->hasMany('App\Models\RegistryJobs', 'employee', 'id');
}
}
class RegistryJobs extends Model
{
protected $table = "registry_jobs";
protected function jobsData()
{
$this->hasManyThrough('App\Models\AnimalRegistry', 'App\Models\RegistryJobsData', 'id', 'animal_registry_id');
}
}
class RegistryJobsData extends Model
{
protected $table = "registry_jobs_data";
public function jobs()
{
$this->belongsTo('App\Models\RegistryJobs', 'id', 'registry_jobs_id');
}
public function animals()
{
$this->hasMany('App\AnimalRegistry', 'id', 'animal_registry_id');
}
}
class AnimalRegistry extends Model
{
protected $table = "animal_registry";
}
And now I am trying to query it from a controller in a way
$data = User::whereHas('jobs', function ($query) {
$query->where('id', 1);
})->get();
But I am unable to access the properties from the animal_registry.
Can you try like this :
public function animals(){
return $this->hasManyThrough('App\Registry_Jobs_data','App\Registry_Jobs', 'employee',
'registry_jobs_id', 'id' ,'id')->join('//Do the joining')->select();
}
Check the hasManyThrough i am not sure..

laravel adding custom another query into releatinship

in laravel i have this query which that work fine,
$months = Month::with(['lessons' => function ($query) {
$query->with(['files']);
}])->get();
in this query i have $query->with(['files']) which that is:
public function files()
{
return $this->hasMany(LessonFiles::class);
}
i want to add this query for all of $query->with(['files']) rows which that have lesson_file_key:
LessonsView::whereLessonFileKey($lessonFile->lesson_file_key)->count()
it means i want to get count of each row of $query->with(['files']) in this query by adding above code, for example:
$months = Month::with(['lessons' => function ($query) {
$req = $query->with(['files']);
// for example using foreach on $req
// LessonsView::whereLessonFileKey($req->lesson_file_key)->count()
}])->get();
my models:
class Month extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id'];
public function lessons()
{
return $this->hasMany(Lesson::class);
}
public function files()
{
return $this->hasMany(MonthFiles::class);
}
}
class Lesson extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id', 'month_id', 'filename', 'file_url'];
public function month()
{
return $this->belongsTo(Month::class);
}
public function files()
{
return $this->hasMany(LessonFiles::class);
}
}
class LessonFiles extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id', 'lesson_id', 'filename', 'file_url'];
public function lesson()
{
return $this->belongsTo(Lesson::class);
}
public function visits(){
return $this->hasMany(LessonsView::class);
}
}
class LessonsView extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id','user_id','lesson_files_id','lesson_file_key','ip_address'];
public function visitedLesson(){
return $this->belongsTo(LessonFiles::class);
}
}
For something like this you could add a views relationship to you LessonFiles model, something like:
public function views()
{
return $this->hasMany(LessonsView::class, 'lesson_file_key', 'lesson_file_key');
}
Then in your query you can use withCount():
$months = Month::with([
'lessons.files' => function ($query) {
$query->withCount('views');
},
])->get();
Use withCount and whereColumn like this:
$months = Month::with(['lessons' => function ($query) {
$query->with(['files' => function($q) {
$q->withCount(['visits' => function($vq) {
$vq->whereColumn('lesson_views.lesson_file_key', 'lesson_files.lesson_file_key')
}]);
}]);
}])->get();

Laravel Complex Relationships Through Polymorphism

I have the following models using Laravel 5.3:
Provider:
// Provider model
$primaryKey = 'id'
public function activities()
{
return $this->hasMany(Activity::class);
}
Activity:
// Activity model
$primaryKey = 'id'
public function provider()
{
return $this-belongsTo(Provider::class);
}
public function semesters()
{
return $this->hasMany(Semester::class);
}
public function semesterPurchases()
{
return $this->hasManyThrough(Purchase::class, Semester::class, 'activity_id', 'purchasable_id')
->where('purchasable_type', Semester::class);
}
Semester:
// Semester model
$primaryKey = 'id'
public function activity()
{
return $this->belongsTo(\App\Models\Activity::class, 'activity_id', 'id');
}
Purchase:
// Purchase model
$primaryKey = 'id'
public function purchasable()
{
return $this->morphTo();
}
In my case Semester::class is the purchasable_type. Is there a way to establish a relationship between Provider::class and Purchase::class? In order to make it possible to do something like this:
$providers = Provider::select('id', 'name', 'address')
->with('purchases')
->where('providers.id', 1)
->get();
I would prefer not to go through activities like so:
$providers = Provider::select('id', 'name', 'address')
->with('activities.purchases')
->where('providers.id', 1)
->get();
which I know I can do using hasManyThrough on the Activity::class
Laravel has no native support for a direct relationship.
I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep
class Provider extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function purchases()
{
return $this->hasManyDeep(
Purchase::class,
[Activity::class, Semester::class],
[null, null, ['purchasable_type', 'purchasable_id']]
);
}
}
Provider::find($id)->purchases;

type casting in laravel json response in relationships eager loading

This is my post model.
class Post extends Model
{
use SoftDeletes;
protected $table = 'posts';
protected $fillable = ['title','featuring_image', 'brief', 'body', 'seen_count'];
public function user(){
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function someComments()
{
return $this->comments()->limit(Constants::COMMENTS_COUNT_LIMIT);
}
public function commentsCount()
{
return $this->comments()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
public function likes()
{
return $this->hasMany(Like::class);
}
public function isLiked()
{
return $this->likes()->where('user_id', auth()->check() ? auth()->user()->id : 0);
}
public function likesCount()
{
return $this->likes()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
}
I executed this query on this model.
$post = Post::with(['categories', 'user', 'commentsCount', 'likesCount', 'isLiked'])->find($post->id);
Because of the relation between this table and like and comment table, The output of this query for 'commentsCount', 'likesCount', 'isLiked' is an array. But I need to receive numbers for 'commentsCount' and 'likesCount', and a boolean for 'isliked' as an output, in laravel josn response.
You might find it easier to use the withCount() the comes with Eloquent instead.
Then for is_liked you could use a scope to get the value and the cast it to a boolean:
public function scopeIsLiked($query)
{
if (is_null($query->getQuery()->columns)) {
$query->select([$query->getQuery()->from . '.*']);
}
$relation = Relation::noConstraints(function () {
return $this->likes();
});
$q = $this->likes()->getRelationExistenceCountQuery(
$relation->getRelated()->where('user_id', auth()->check() ? auth()->user()->id : 0)->newQuery(), $query
);
$query->selectSub($q->toBase(), 'is_liked');
}
Please note you will need to add the use statement for Relation to the top of the class:
use Illuminate\Database\Eloquent\Relations\Relation;
You model could then look like:
class Post extends Model
{
use SoftDeletes;
protected $table = 'posts';
protected $fillable = ['title', 'featuring_image', 'brief', 'body', 'seen_count'];
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function someComments()
{
return $this->comments()->limit(Constants::COMMENTS_COUNT_LIMIT);
}
public function likes()
{
return $this->hasMany(Like::class);
}
/**
* Scope to add the "is_liked" flag.
*
* #param $query
*/
public function scopeIsLiked($query)
{
if (is_null($query->getQuery()->columns)) {
$query->select([$query->getQuery()->from . '.*']);
}
$relation = Relation::noConstraints(function () {
return $this->likes();
});
$q = $this->likes()->getRelationExistenceCountQuery(
$relation->getRelated()->where('user_id', auth()->check() ? auth()->user()->id : 0)->newQuery(), $query
);
$query->selectSub($q->toBase(), 'is_liked');
}
}
And your query would look something like:
$post = Post::with('categories', 'user')
->withCount('likes', 'comments')
->isLiked()
->find($post->id);
Hope this helps!
You can use Laravel casts:
Inside the each model you can add the following to cast a value, per example:
protected $casts = [
'isLiked' => 'boolean',
];
Rwd's answer gives a nice solution using scopes, but for laravel 5.4+ you could get away with aliasing the withCount() result and then casting it to boolean with a $cast variable on the model or an accessor (with accessor, you can only get snake case is_liked). This way we don't need to write complex scopes.
The model would be
class Post extends Model
{
// rest of model
protected $casts = ['isLiked'=>'boolean'];
public function likes()
{
return $this->hasMany(Like::class);
}
}
Then in your controller
$post = Post::with('categories', 'user')
->withCount(
[
'likes as likesCount', 'comments as commentsCount',
'likes as isLiked' =>function($query){
$query->where('user_id', auth()->check() ? auth()->user()->id : 0);
}
]
)
->find($post->id);
And now you get likesCount (int), commentsCount (int) and isLiked (boolean)

Laravel - Retrieving specific column from a releted query

I have 4 tables:
conversations
- id (pk)
- userId1 (fk)
- userId2 (fk)
users
- id (pk)
- name
- surname
.
.
.
- roleId (fk)
- userStatusId (fk)
roles
- id (pk)
- type (fk)
user_status
- id (pk)
- description (fk)
this are my models:
class Conversation extends Eloquent {
public function user1(){
return $this->hasOne('User', 'id', 'userId1');
}
public function user2(){
return $this->hasOne('User', 'id', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->hasOne('Role', 'id', 'roleId');
}
public function userStatus(){
return $this->hasOne('UserStatus', 'id', 'userStatusId');
}
// public function conversation1(){
// return $this->belongsToMany('Conversation', 'id', 'userId1');
// }
// public function conversation2(){
// return $this->belongsToMany('Conversation', 'id', 'userId2');
// }
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->belongsToMany('User', 'id', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->belongsToMany('User', 'id', 'roleId');
}
}
Now what I want to do is, for example, take all the conversations where the "userId1" (on conversations) is of a "user" who have the status "description" equal to "registered".
That's what I do:
Route::get('/', function(){
$conversation = Conversation::with(array('user1.userStatus' => function ($query){
$query->where('description', '=', 'registered');
}))->get();
foreach ($conversation as $conv) {
echo '<br \>';
echo $conv;
}
});
I expect to receive all the conversations record where the status of the userId1 is "registered" and nothing else... Instead what I receive are all the conversations records and, for each one, the user records and the records of the userStatus table (of this last I receive just the one who match the where clause and the ones who are not have a null value).
I know my english is terrible but I hope someone could understand and help me. Thanks!
All your relations are wrong. You need to read http://laravel.com/docs/eloquent#relationships and in your case it's:
class Conversation extends Eloquent {
public function user1(){
return $this->belongsTo('User', 'userId1');
}
public function user2(){
return $this->belongsTo('User', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->belongsTo('Role', 'roleId');
}
public function userStatus(){
return $this->belongsTo('UserStatus', 'userStatusId');
}
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->hasMany('User', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->hasMany('User', 'roleId');
}
}
Now, to retrieve only those conversations you want this:
Conversation::whereHas('user1', function ($q) {
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
})->get();
or using this PR https://github.com/laravel/framework/pull/4954
Conversation::whereHas('user1.userStatus', function ($q) {
$q->where('description', 'registered');
})->get();
Also, to make it more verbose, you can wrap that code in a scope:
// User model
public function scopeRegistered($query)
{
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
}
then:
Conversation::whereHas('user1', function ($q) {
$q->registered();
})->get();
You may try this:
$conversations = Conversation::whereHas('user1.userStatus', function ($query){
$query->where('description', '=', 'registered');
})->get();
This will return only the Conversation models whose related user1.userStatus is registered.

Resources