I have many to many relationship between the models KSMschema and NORM
$normen = Ksmheader::find(15)->norms;
foreach($norms as $item){
echo $item->number;
}
Now i get a list of norms. This is one example:
[{"id":18,"certificaten_id":5,"nummer":"1.2.3","text":"Text van nog een norm.","created_at":"2014-02-14 15:14:05","updated_at":"2014-02-14 15:14:20","deleted_at":null,"pivot":{"ksmheader_id":9,"norm_id":18}}
But now i also need to sort them on a second column 'column_id'
$normen = Ksmheader::find(15)->normen->where('certificates_id', '=', 6);
This does not seem to work. What am i doing wrong?
Please check that you are using the correct function to get the norms :
Ksmheader::find(15)->norms->where('certificates_id', '=', 6);
What error/exception do you get if you try the above code?
Thanx all for you suggestions. I just found the answer myself.
For anyone who wants to know:
I first added the () after 'normen'. Just as deczo suggested.
Then i added a ->get()
normen = Ksmheader::find($ksmSchemaRow->ksmheader_id)->normen()->where('certificaten_id', '=', 5)->get();
foreach($normen as $item){
echo $item->nummer;
//echo 'NAME';
echo '/';
}
I added get() now i get the results i want.
Related
I have two tables, products and product_images, now I want to show product which has at least one image.
In controller I have a simple function in ProductController to fetch all the products:
public function products(){
$allProducts = $this->product->paginate(15);
return view('frontend.pages.products',compact('allProducts'));
}
But, I want to send the products which has at least one image of each product.
What should I do to achieve that?
Edit:
I have created relationship between tables, now how can I get my desired answer?
I have written this in the Controller:
$allProducts = $this->product->whereHas('product_images', function ($query){
$query->where();
})->get();
Assuming table schema
product
-id
-name
product_image
-id
-product_id
-url //any columns you needed
$product_ids = DB::table('product')
->join('product_image','product_image.product_id','=','product.id')
->select('product.id','roduct.name')
->groupBy('product.id')
->get();
$product_count = count($product_ids);
Eloquent has this built in.
Example
// Retrieve all posts that have three or more comments...
$posts = App\Post::has('comments', '>=', 3)->get();
In your case
In your case you could change the $allProducts line to be
$allProducts = $this->product()->has('product_image', '>=', 1)->paginate(15);
I didn't test the code above.
See documentation for more information on this topic.
https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence
You can use selectRaw:
$products = Product::leftJoin('product_images',function ($join){
$join->on('products.product_id','=','product_images.product_id');
})->selectRaw("products.product_id i, count(product_images.id) c")
->groupBy('products.product_id')
->where('c','>=',3)
->get();
Getting answer querying realtionship:
The query will look like following:
$allProducts = $this->product->has('Images')->paginate(15);
But, make you sure you have created relation in Model like the following:
public function Images(){
return $this->hasMany('\App\Models\ProductImages');
}
I have used hasMany relationship because one product can have multiple images.
How can I make withCount('comments') also include all deleted/trashed rows?
For example, if I have 5 comments, and I delete 1, I still expect withCount('comments') to return 5, but instead it's returning 4.
My full query looks something like this:
$query = Post::withTrashed()
->withCount('comments')
->get();
I think you can try this
$query = Post::withCount('comments')
->withTrashed()
->get();
OR
$query = DB::table('post')
->select('comments', DB::raw('count(*) as comments'))
->get();
Hope this work for you!
Since laravel doesn't propose a way to filter the relation when using withCount, a clean solution would be to declare the relation and add the withTrashd() to it.
In Post.php
public function commentsWithTrashed()
{
return $this->comment()->withTrashed();
}
Now you can use the withCount on it.
$query = Post::withTrashed()
->withCount('commentsWithTrashed')
->get();
You can add this to count
$query = Post::withCount(['comments'=> function ($query) {$query->onlyTrashed();])
->get();
it works properly.
You can use the withTrashed method:
>withTrashed()
I try to make a particular query but i'm not sure how to achieve this , i would like to access to saison table
{{ \App\Licencies::where(['structure_id' => Auth::user()->structure->id])->where(['saison_id->dt_fin' , '<' , \Carbon\Carbon::now()])->count() }}
here the saison() relation in my model , that i can access very well
$licencie->saison->dt_fin < \Carbon\Carbon::now()
someone knows to right query ? thanks a lot in advance
Thanks for the explanation in the comment.
In the Laraval documentation there is the following example:
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
Which can easily be transformed for your purpose:
// Retrieve all licencies where the saison has a dt_fin before now
$licencies = \App\Licencies::whereHas('saison', function ($query) {
$query->where('dt_fin', '<', \Carbon\Carbon::now());
})->get();
If it still returns errors, let us know! (kinda hard to test without carbin and a structure that is equal to yours)
Got a question if anyone can help out.
I have a query that has a collection of parameters and displays some results.
DB::table()
->join()
->where()
->orderby()
->select()
->get();
But the wheres are generated by a form input in the view. Basically this is a bunch of filters to get a table of results. I want to paginate that. if I change the get() to paginate(), and call $result->links() in the template, it does indeeed paginate and generates a bunch of results for me, however the problem is that when you move away from page 1, the links are just a _GET parameter and all the filter input does not get applied.
Is there a way I can have the pagination AND filters going at the same time? What is the laravel way of handling that? Or would I have to build some way of handling filters and pages? Any tips on that?
Cheers!
* Solution *
The solution was to make the form use GET method and persist the old filters to the Pagination using ->appends() method. Below is the modified code to do that if anyone else is looking.
$results = $query->paginate($this->report->inputs->per_page);
$query = array_except( Input::query(), Paginator::getPageName() );
$results->appends($query);
Yes, here's how I do it:
$orderBy = Input::get('orderBy', 'created_at');
$order = Input::get('order', 'DESC');
$limit = Input::get('limit', 100);
$name = Input::get('name', '');
$result = DB::table()
->where('name', 'LIKE', '%' . $name . '%')
->orderBy($orderBy, $order)
->paginate($limit);
Hey guys how you doing?
I'm trying to simply find by id and at the same time guarantee that a column from a relationship table is with a value.
I tried a few things but nothing works.
$tag = Tag::find($id)->whereHas('posts', function($q){
$q->where('status','=', 1);
})->get();
Also:
$tag = Tag::whereHas('posts', function($q) {
$q->where('status','=', 1);
})->where('id','=', $id)->get();
Can you help me?
It is a simple thing but I can't manage to do it...
You need to read on Eloquent docs. Learn what's find, first, get for that matter.
Your code does what you need, and more (a bit wrong though) ;)
$tag = Tag::find($id) // here you fetched the Tag with $id
->whereHas('posts', function($q){ // now you start building another query
$q->where('status','=', 1);
})->get(); // here you fetch collection of Tag models that have related posts.status=1
So, this is what you want:
$tag = Tag::whereHas('posts', function($q){
$q->where('status','=', 1);
})->find($id);
It will return Tag model or null if there is no row matching that where clause OR given $id.
Have you checked Query Scope ?
You can do this:
$tag = Tag::where('status', '=', 1)
->where('id', '=', 1, $id)
->get();