I'm converting roject from pure PHP to Laravel 4, and I have a problem with converting this query
SELECT * FROM verses,thoughts WHERE verses.id != thoughts.verses_id
I have two tables verse and thought. one verse has one thought. when creating a thought i want to display all the verse whose thoughts has not been created . Im using Laravel 4.2 display the verses it is not listed in thoughts
Did you read the docs?
DB::table('thoughts')
->join('verses', 'verses.id', '!=', 'thoughts.verses_id')
->get();
Related
I have been working with a laravel 5.3 version and in a table i have a json column where i have saved average rating of a category table.
so, A product category table has a column "detail" as a json data type which saves avgRating.
I want to run a query inside that json column. And i want to filter that category with a average rating. So, from the frontend side rating comes in a parameter with a comma seperated so that category can be filtered with multiple ratings.
$productCategory = ProductCategory::query();
$ratings = explode(',',$params['ratings']);
$productCategory = $productCategory->whereIn('detail->avgRating',$ratings)->get();
I want to achieve something like this.
I am using Postgres
It turns out that there was too much uncertainty at the time when the question was asked. Once the asker separated the problems and figured out that the raw query of
DB::select(DB::raw("SELECT * FROM product_categories where detail->>'avgRating' in ('2.0','4.0')"));
works in Postgres, the asker from that point onwards had a much easier time figuring out the actual solution in the where clause. I presuppose that it was
detail->>avgRating
instead of
detail->avgRating
but from the comment section that was not yet confirmed. But the moral of the story is that whenever one has an eloquent problem that might be related to the RDBMS, then it makes a lot of sense to first sort out the raw query and then, having solid knowledge about what should be generated, at that point one can switch to the Eloquent code and apply the solution there.
You should use whereJsonContains or whereRaw:
$productCategory->whereJsonContains('detail->>avgRating',$ratings)->get();
OR
$productCategory->whereRaw('JSON_CONTAINS(detail->>avgRating, ?)', $ratings)->get();
I have a countif query in mysql and I would like to show the table on my html. I'm currently using laravel 6.0 framework.
Here is the picture of the table i want to show:
Here is my code in html:
Here is my code in the controller:
There should be numerous errors with index function in your controller. Specifically with how you are trying to assign $count a value. Read these: Eloquent Methods all() vs get(), Eloquent Selects, Eloquent Ordering, Grouping, Limit and Offset, Eloquent Where.
Laravel has an excellent documentation, if you were to follow it - working with Laravel would become much easier.
I am using Laravel 4 and the Eloquent model for a project we are working on.
The database conforms to 3NF and everything works great. Also all MySQL tables were switched back from InnoDB to MyISAM since the MySQL version < 5.6 (full text search in InnoDB is only supported from 5.6 and up).
While creating some database search filters I am finding some shortage with using the Eloquent model vs the Query Builder. In specifics, especially when trying to do a full text search on columns from multiple tables (and staying within the Eloquent's object context).
For simplicity, we have the following database structure:
--projects
--id
--name
--status
--...
--users
--id
--...
--roles
--id
--project_id
--user_id
--...
--notes
--id
--project_id
--user_id
--note
--....
The following code (simplified and minimized for the question) currently works fine, but the full text search only works for one table (projects table).
if (Request::isMethod('post'))
{
$filters = array('type_id','status','division','date_of_activation','date_of_closure');
foreach ($filters as $filter) {
$value = Input::get($filter);
if (!empty($value) && $value != -1) {//-1 is the value of 'ALL' option
$projects->where($filter,'=',$value);
}
}
$search = Input::get('search');
if (!empty($search)) {
$projects->whereRAW("MATCH(name,description) AGAINST(? IN BOOLEAN MODE)",array($search));
}
}
// more code here...
// some more filters...
// and at the end I am committing the search by using paginate(10)
return View::make('pages/projects/listView',
array(
"projects" => $projects->paginate(10)
)
);
I need to extend the full text search to include the following columns - projects.name,projects.description and notes.note.
When trying to find how to make it with Eloquent we keep on coming back to Query Builder and running a custom query, which will work fine but then we will face these problems/cons:
Query Builder returns an array while Eloquent returns model objects. Since we are extending each model to include methods, we really don't want to give up the awesomeness of the Eloquent model. And we really don't want to use the Eloquent Project::find($id) on the return results just to get the object again.
We are chaining the 'where' methods to have any number of filters
assigned to it as well as for code re-usability. Seems like mixing
Eloquent and Query Builder statement together will break our chaining.
For the consistency of this project, we want all database queries to
stay in Eloquent connotation.
Reading Laravel's documentation and API, I could not find a method to run raw SQL queries using Eloquent. There is whereRAW() but it is not broad enough. I assume that this is a restriction made by design, but it is still a restriction.
So my questions are:
Is it possible to run a full text search on columns from multiple tables, only in Eloquent. Every piece of information I came across online, mentions using Query Builder.
If not, is it possible to use Query Builder searches and returning Eloquent objects? (without the need to run Project::find($id) on the array results).
And lastly, is it possible to chain Eloquent and Query Builder where methods together, while only committing using get() or paginate(10) at a later point.
I understand that Eloquent and Query Builder are different creatures. But if mixing both was possible, or using Eloquent to run raw SQL queries, I believe that the Eloquent model will become much more robust. Using only Query Builder seems to me a bit like under-using the Laravel framework.
Hope to get some insights about this since it seems as the forums/community of Laravel is still evolving, even though I find it to be an amazing framework!
Thanks and I appreciate any input you may have :)
First of all you can use query scope in your model/s
public function scopeSearch($query, $q)
{
$match = "MATCH(`name`, `description`) AGAINST (?)";
return $query->whereRaw($match, array($q))
->orderByRaw($match.' DESC', array($q));
}
this way you can get "eloquent collection" as return
$projects = Project::search(Input::get('search'))->get();
then, to search also into notes you can make a more complex scope that join notes and search there.
Not sure if this will help but there is a workaround in innoDB(in versions that support fulltext search), maybe it works for you.
Lets use 'notes' as second table
SELECT MATCH(name,description) AGAINST(? IN BOOLEAN MODE),
MATCH(notes.note) AGAINST(? IN BOOLEAN MODE)
FROM ...
.
WHERE
MATCH(name,description) AGAINST(?) OR
MATCH(notes.note) AGAINST(?)
So far I have the following model:
class Listing extends Eloquent {
//Class Logic HERE
}
I want a basic function that retrieves the first 10 rows of my table "listings" and passes them on to the view (via a controller?).
I know this a very basic task but I can't find a simple guide that actually explains step-by-step how to display a basic set of results, whilst detailing what is required in the model, controller and view files.
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
pagination docs
passing data to views
Eloquent basic usage
A cheat sheet
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
Another way to do it is using a limit method:
Listing::limit(10)->get();
This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:
Listing::inRandomOrder()->limit(10)->get();
this worked as well IN LARAVEL 8
Model::query()->take(10)->get();
This also worked in Laravel 9
Model::query()->take(10)->get();
I'm using Laravel 4 and I'm running into an issue with eloquent.
I've got it set up to grab the category, get the products and limit it to 2. However I'm having trouble getting the random element. I need it to select from two random products, rather than the newest/latest.
$products = Category::find($id)->products->take($limit);
$products->load('imageThumb');
return $products;
I'd like to keep the solution eloquent based, but if that's not an option I'll switch to a raw query code.
Thanks!
$products = Category::find($id)->products()->orderBy(DB::raw('RAND()'))->take($limit)->get();
(sorry forgot the ->get() in my original answer)
How's big is the table? If it is not too big you can use MySQL ORDER BY RAND()
http://davidwalsh.name/mysql-random
Eloquent something like:
->orderBy(DB::raw('RAND()'))