Laravel incoporating a count in a DB query - laravel-5

I have two tables, properties and photos with a basic code of
$pr = DB::table('properties')
->leftJoin('photos', 'properties.id', '=', 'photos.property_id')
->select(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired']);
I would like to count the number of photos to each property and incorporate it into the select as something like noPhotos.
I seem to be stuck on this!
Thanks!

I worked it out:
$pr = DB::table('properties')->leftJoin('photos', 'properties.id', '=', 'photos.property_id')->select(DB::raw('count(photos.id) as photos_count'))->addSelect(['properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired'])->groupBy('properties.id', 'address', 'town', 'postcode', 'units','unitType','examination','priority','completed','quotationRequired')->get();

Related

Laravel eager not working with select function

If I use select function the data disappears
$regions = Region::select('id', 'place_id', 'formatted_address')
->where('lang', $lang)
->with(['areas' => function($query) {
return $query
->select('id', 'place_id', 'formatted_address') // << the problem is here
->whereNotNull('area1')->whereNull('locality')->whereNull('area2');
}])
->get();
if you remove the select function, the areas field is filled with data
Relations:
$this->hasMany(Region::class, 'country', 'formatted_address');
The request must contain fields that participate in the relationship
$this->hasMany(Region::class, 'country', 'formatted_address');
->select('place_id', 'country', 'formatted_address')

How can we alias the name of a child table column without using select in Laravel Eloquent

Category Table Field:'id', 'title', 'slug'
Blog Table Field:'id','title', 'slug', 'short_desc', 'detail_desc', 'publish_date', 'seo_title', 'seo_keywords', 'seo_description', 'image', 'view_count', 'status'
My query is fine with this syntax :
$data['rows'] = Blog::select('blogs.id','blogs.title', 'blogs.slug', 'blogs.short_desc', 'blogs.detail_desc', 'blogs.publish_date','blogs.seo_title', 'blogs.seo_keywords', 'blogs.seo_description', 'blogs.image', 'blogs.view_count', 'blogs.status', 'cat.id as cat_id')
->join('categories as cat', 'blogs.category_id', '=', 'cat.id')
->paginate($this->pagination_limit);
i want to create this type of syntax with alise category id:
$data['rows'] = Blog::join('categories', 'blogs.category_id', '=', 'categories.id')
->paginate($this->pagination_limit);
So, how can i change categories table id as cat_id without using select. Because when i use without select and use blog id, it relapsed with category id.
Use addSelect like this:
$data['rows'] = Blog::join('categories', 'blogs.category_id', '=', 'categories.id')
->select('*')
->addSelect('categories.id AS cat_id', 'blogs.id AS id') // alias categories id and rewrite the id for blogs
->paginate($this->pagination_limit);

Laravel displaying elements distinctly

public function employeebanvisitor(Request $request) {
$vis = bookingmodel::distinct('visitorname')
->select(
'id',
'visitorname',
'visitorphonenumber',
'compname',
'designation'
)
->where('empmail',Auth::user()->email)
->get();
return view('employee.employeebanvisitor',compact('vis'));
}
In the above query i need to display the list distinctly where the the distinct element is visitorname.But this command does not return elements distinctly.Any Help or suggestion is most welcomed.
try this :
$vis = bookingmodel::select(
'id',
'visitorname',
'visitorphonenumber',
'compname',
'designation'
)
->where('empmail',Auth::user()->email)
->distinct('visitorname')
->get();
Distinct does not take any argument in laravel. You can refer to the laravel api. But what you can do is you can set the column that you want to set as distinct to be the first column in your select statement for it to work.
$vis = bookingmodel::select(
'visitorname',
'id',
'visitorphonenumber',
'compname',
'designation'
)
->distinct()
->where('empmail',Auth::user()->email)
->get();

Ordering Results from Related Tables in Eloquent and the Session

I have the following in my Event model in Laravel 4. The reason I am using QueryBuilder and not Eloquent is I need to have links in each column header in my results table in my view, that when clicked, order the results in asc or desc based on that column.
The issue I'm having is, if I use Eloquent, it won't work as most of the data is pulled through via relationships to other tables, so Eloquent can't find the required columns/fields.
public static function getEvents($perPage = 10)
{
$order = Session::get('event.order', 'start_date.desc');
$order = explode('.', $order);
$columns = array(
'events.id as id',
'title',
'locations.city as city',
'suppliers.name as supplier_name',
'venues.name as venue_name',
'start_date',
'courses.price as course_price',
'type',
'status',
'max_delegates as availability',
'tutors.first_name as tutor_first_name',
'tutors.last_name as tutor_last_name',
'contacts.first_name as d_first_name'
);
$events = DB::table('events')
->leftJoin('courses', 'course_id', '=', 'courses.id')
->leftJoin('suppliers', 'supplier_id', '=', 'suppliers.id')
->leftJoin('locations', 'location_id', '=', 'locations.id')
->leftJoin('venues', 'venue_id', '=', 'venues.id')
->leftJoin('event_types', 'event_type_id', '=', 'event_types.id')
->leftJoin('event_statuses', 'event_status_id', '=', 'event_statuses.id')
->leftJoin('tutors', 'tutor_id', '=', 'tutors.id')
->leftJoin('delegate_event', 'delegate_event.event_id', '=', 'events.id')
->leftJoin('delegates', 'delegates.id', '=', 'delegate_event.delegate_id')
->leftJoin('contacts', 'delegates.contact_id', '=', 'contacts.id')->groupBy('events.id')
->select($columns)
->orderBy($order[0], $order[1])
->paginate($perPage);
return $events;
}
If you look at my EventsController at the getOrder method:
public function getOrder($order)
{
Session::put('event.order', $order);
return Redirect::back();
}
You can see I am storing the order in the session and then in my model using that to sort the order of results.
Is there a way to do this in Eloquent the way I need to?
You know you can just add a join() to eloquent right?
So, as an example, if you have users and each user has some blog posts (i.e. user has_many blogs), you can output an eloquent model showing username and blog title, ordered by blog title, as follows:
user::join('blogs', 'blogs.id','=','users.blog_id')
->order_by('blogs.title', 'asc')
->select(array('users.username', 'blogs.title'))
->paginate(10);

Laravel QueryBuilder where clause with user info on other model

I have a Model ImageRequest that is related to my User model like this:
public function user()
{
return $this->belongsTo('App\User');
}
An my User model like this:
public function imageRequests()
{
return $this->hasMany('App\ImageRequest');
}
Now I use this package to build my filterable query to fetch all ImageRequests:
spatie/laravel-query-builder
this is what my query looks like:
$query = QueryBuilder::for(ImageRequest::class)
->with(['requestTypes'])
->allowedIncludes('requestTypes')
->orderByRaw("FIELD(status , 'new') desc")
->orderBy('functional_id', 'asc')
->allowedFilters(
'id',
'pv_number',
'created_at',
Filter::scope('starts_between'),
'location_of_facts',
'train_nr',
'status',
'result_of_search',
Filter::custom('type', RequestTypeFilter::class)
);
I need to add a where clause for the User model something like this:
->where('zone', Auth::user->zone);
But it says:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'zone' in 'where clause' (SQL: select count(*) as aggregate from image_requests where zone = a)
Please look into this code, Here I added a whereHas instead for where. so it will take only matching records to user table for desired zone.
hope it helps..
$query = QueryBuilder::for(ImageRequest::class)
->with(['requestTypes'])
->whereHas('user'=>function($q){
$q->where('zone', Auth::user->zone);
})
->allowedIncludes('requestTypes')
->orderByRaw("FIELD(status , 'new') desc")
->orderBy('functional_id', 'asc')
->allowedFilters(
'id',
'pv_number',
'created_at',
Filter::scope('starts_between'),
'location_of_facts',
'train_nr',
'status',
'result_of_search',
Filter::custom('type', RequestTypeFilter::class));
Please have try this, used direct join query.
$query = ImageRequest::selectRaw('column1,column2')
->join('user', function($join){
$join->on('ImageRequest.user_id','=','user.id');
})
->leftJoin('request_types', function($join){
$join->on('request_types.image_request_id','=','image_request.id')
})
->where('user.zone', Auth::user->zone)
->orderByRaw("FIELD(status , 'new') desc")
->orderBy('functional_id', 'asc')
->allowedFilters(
'id',
'pv_number',
'created_at',
Filter::scope('starts_between'),
'location_of_facts',
'train_nr',
'status',
'result_of_search',
Filter::custom('type', RequestTypeFilter::class)
);

Resources