Cant get laravel query with relationship - laravel

I have model class Post with relationship
function postanchors(){
return $this->hasMany('App\PostAnchors', 'post_id', 'id');
}
posts_anchors is simple table
id | post_id | anchor_id
Now I want to get posts if they has anchor_id = 51
$query = Post::query();
$posts = $query->with('postanchors', function ($query){
$query->where('anchor_id','=', 51);
})
error mb_strpos() expects parameter 1 to be string, object given
$posts = $query->with('postanchors')->where('anchor_id', 51)->paginate(8);
does not working too
Undefined column: 7 ERROR: column "anchor_id" does not exist LINE 1: select count() as aggregate from "posts" where "anchor_id"*
It mast be simple request. May be relationship wrong?

try below query:
$query = Post::query();
$posts = $query->whereHas('postanchors', function ($query){
$query->where('anchor_id','=', 51);
})->get();

Related

Order by relationship with pagination laravel eloquent

I have the relationship below, an application belongs to a user.
Users table
ID | Name
1 | Danny
2 | Mark
Applications table
ID | user_id
1 | 1
2 | 2
Application.php
public function user()
{
return $this->belongsTo(User::class);
}
I'm trying to sort the application by user's name and paginate the result. I tried the code below, the pagination is working but the order by doesn't have any effect.
$query = Application::query();
$query = $query->with(['user' => function ($query){
$query->orderBy('name', 'DESC');
}]);
$query = $query->paginate(10);
Try using inner join and order by relation column:
$applications = Application::select('*')
->join('authors', 'applications.user_id', '=', 'users.id')
->orderBy('authors.name', 'DESC')
->paginate(10);
Try this:
Application::join('users', 'applications.user_id', '=', 'users.id')
->orderBy('users.name','desc')
->with('users')
->get();

Call to undefined method Illuminate\Database\Query\Builder::exchanges()

ERROR: BadMethodCallException in Builder.php line 2435:
Call to undefined method Illuminate\Database\Query\Builder::exchanges()
There are two tables, named as EXCHANGES table and FINALTRADES table.
Exchanges table has START_TIME field (with format : 00:00:00) and finaltrades table has exchange_id.
I want to count entries only which come between start_time to start_time+1hrs from final trades table. FOR EXAMPLE: If start_time has 09:15:00, then count between 09:15:00 to 10:15:00 records only.
Function:
public function getCountHour() {
$user_id = Auth::user()->id;
$countTrades = FinalTrade::where('user_id', '=', $user_id)
->exchanges()
->where('start_time', '>=', $your_desired_time)
->where('start_time' , '<=' , strtotime($your_desired_time) + 60*60)
->count();
return response()->json($countTrades);
}
Relationship given to FnalTrade model:
public function exchanges(){
return $this->hasOne('App\EXCHANGE_MODEL_NAME', 'id', 'exchange_id');
}
both table SCREEN
The following should do the trick:
$countTrades = FinalTrade::whereUserId(Auth::id())
->whereHas('exchanges', function($query) use ($your_desired_time) {
$query
->where('start_time', '>=', $your_desired_time)
->where('start_time' , '<=' , strtotime($your_desired_time) + 60*60);
})
->count();

Laravel Repositories whereHas -- multiple

I have the following repository Products and each product can have many Categories and many Bidders
What I am trying to achieve is the following (Without Repository)
$products = Products::whereHas('categories', function ($category) {
})->whereHas('bidders', function ($bidder) {
})->get();
This works fine, however, I am trying to make it so that repositories are in place and you can still do the whereHas query, so in my repository I created a method:
public function whereHas($attribute, \Closure $closure = null)
{
return $this->model->whereHas($attribute, $closure);
}
This works well, but only if I am using one of them in my main query, whereas if I use multiple:
$products = $this->products->whereHas('categories', function ($category) {
$category->where('id', '=', 1);
})->whereHas('bidders', function($bidders) {
})->get();
I am getting the following error:
Unknown column 'has_relation'
Column not found: 1054 Unknown column 'has_relation' in 'where
clause' (SQL: select * from products where exists (select * from
categories inner join products_categories on categories.id =
products_categories.categories_id where products.id =
products_categories.products_id and id = 1) and (has_relation
= sections))
The issue I'm seeing is that its returning a collection of items on the first whereHas which means it cannot compute the second one. Any ideas to where I am going wrong?
You can pass a closure with multiple relations to whereHas
$products = $this->products->whereHas(['categories', function
($category) {
$category->where('id', '=', 1);
},'bidders' => function($bidders) {
}])->get();
It will work as expected.

How to use query scope in join request Laravel?

I have the following request:
$objects = Object::with("translate")->where(function ($query) use ($request) {
$query->language();
})->with('images')->with("category")->orderBy('id', 'desc')->paginate($limit);
So, in model Object there is method: translate:
public function translate()
{
return $this->hasMany("App\ObjectTranslate", "objectId", "id");
}
So, also in this model is:
public function scopeLanguage($query)
{
$languageHeader = new ModelLibrary();
return $query->where('language', '=', $languageHeader->getLanguage());
}
When I try to call scope in main request:
$query->language();
I get SQL error:
Column not found: 1054 Unknown column 'language' in 'where clause' (SQL:
You need to join the query with ObjectTranslate's table. your scopeLanguage() function will not work , since you are trying to access the column language which is not available in Object model column.
Note : With() will just eager loading, which will load the eloquent defined function, you cannot directly access their column in where clause.
Modify your scopeLanguage function
public function scopeLanguage($query)
{
$languageHeader = new ModelLibrary();
return $query->join('object_translate_table','object_translate_table.objectId','=','object_table.id')->where('object_translate_table.language',$languageHeader->getLanguage());
}
$objects = Object::with("translate","images","category")
->language()
->orderBy('id', 'desc')
->paginate($limit);
This should work
Assumin ObjectTranslate model's table name is object_translate_table and Object model's table name is object_table

Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

I have the following relationship functions in my Job model:
public function resourceTypes(){
return $this->belongsToMany('ResourceType', 'job_requests');
}
public function resources(){
return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');
}
I am able to get an object with data from both of the above relationships using:
$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();
I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.
How would I do this?
Try something like this:
$job = Job::with('resources' => function($q) {
$q->with('resourceTypes')->where('flow_type',2);
})->findorfail($projectId);
In above you will get only those resources with flow_type = 2
I ended up using the following statement:
Job::with(['resources' => function ($query){
$query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
$result = DB::table('job')
->join('job_resources', 'job.id', '=', 'job_resources.job_id')
->join('job_requests', 'job_resources.request_id', '=', 'job_requests.id')
->where('job_resources.flow_type', '=', CONDITION)
->get();
Your table data is not clear from your input, but this method (query builder) should work

Resources