How Laravel generates SQL queries - php

I have created a one-to-many relationship. Here are the model classes.
class Photo extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
class User extends Authenticatable
{
public function photos(){
return $this->hasMany('App\Photo');
}
}
Then I try to retrieve photos:
$photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();
Here is a query log I got. I do not see the photo='ut.jpg'. So how laravel generate SQL?
select * from `photos` where `photos`.`user_id` = 1 and `photos`.`user_id` is not null

Try this
$photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
must be use ->photos() instead of ->photos.
For see sql query use
$sql = User::find(1)->photos()->where('photo', 'ut.jpg')->toSql();

You queried all photos by using this:
$photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();
By using User::find(1)->photos you receive a Laravel Collection. Those collections have a where method as well. So basically, you are running SQL to get all photos of User 1 and then you just filter that collection to only show you the item with photo ut.jpg.
Instead, you can use brackets to get the relationship, and then query that.
Your query then becomes
$photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
Instead of naming it $photos you should name it $photo, as you are querying with first - which will result only in one object (or null).

Can you please try this:
$photo = 'ut.jpg';
$photos = User::find(1)->whereHas('photos', function ($query) use($photo){
return $query->where('photo', $photo);
})->first();

your query $photos = User::find(1)->photos->where('photo', 'ut.jpg')->first(); is incorrect, laravel didnt see the where condition if you do this
User::whereHas('photos', function($q) {
$q->where('photo', 'ut.jpg');
})->where('id',1)->first();
thats the correct query to get the user photo

You could:
Run A Select Query
$photos = DB::select('select * from photos where id = ?', [1]);
All this is well-documented in :
--https://laravel.com/docs/5.0/database

Related

LARAVEL: How to fetch id dynamically in a query builder?

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}

get last id form database in laravel-8

I want to get only the last inserted data from my database.
Here, I get all data from the database but I want only the last value.
This is ProductController.php
function indextwo()
{
return DB::select("select * from products");
}
This is web.php
Route::get('products_link', [ProductController::class, 'indextwo']);
Here is my current output:
You can get the last id using Query Builder and Eloquent.
Query Builder
function indextwo() {
return DB::table('products')->orderBy('id', 'DESC')->first();
}
Eloquent
function indextwo() {
return Product::orderBy('id', 'DESC')->first();
}
Maybe you can use latest() function for get
$user = DB::select("select * from products")
->latest()
->first();
Maybe you can use Model name direct in controller like your model name is "Product" and also use limit() and latest()
$user = Products::latest()->limit(1);
A very simple way you can follow
Product::query()->latest()->first()
It will return you the latest inserted data according to order by id desc.
Another way :
Product::query()->orderByDesc('id')->first();

Laravel Where Search Query

I have a Spaces and an Interests table.
I am currently able to get a list of the Space Id's saved as $spaceList but I want my $query variable to retrieve a list of interests that the space_id foreign key matches one of the space_id's from my $spaceList variable.
public function index() {
$user_id = auth()->user()->id;
$user = User::find($user_id);
$spaceList = Space::where('user_id', $user_id)->pluck('space_id')->toArray();
$query = Interest::where('space_id', $spaceList);
$interests = $query->get();
return view('dashboard')->with('space', $user->space)->with('interest', $interests);
}
Thanks, I've been at this for ages now.
you should use whereIn instead of where
$spaceList = Space::where('user_id', $user_id)->pluck('space_id')->toArray();
$query = Interest::whereIn('space_id', $spaceList);
In Laravel Eloquent, this is what the Querying Relationship Existence working on
You won't need the $spaceList variable here if it's not used in other places
$query = Interest::whereHas('spaces', function($query) use ($user_id) {
$query->where('user_id', '=', $user_id);
});
Please notice, to get this work, you'll need to declare the spaces one-to-many relation in the Interest Module
Should be something like this, more details see document here
namespace App;
use Illuminate\Database\Eloquent\Model;
class Interest extends Model
{
public function spaces()
{
// space_id is the column name in your space database table
// id the the foreign-key target, generally is the primary-key of space table
return $this->hasMany('App\Space', 'space_id', 'id');
}
}

Laravel 4 whereIn and many to many

I have a tag system, where you can add tags to photos and users.
I have a function where the users are able to add their favorite tags, and select images based on those tags
But my problem i am a really big beginner with php and laravel and i do not know how to pass the values to the whereIn function
Model
public function tag()
{
return $this->belongsToMany('Tag', 'users_tag');
}
Controller
// get the logged in user
$user = $this->user->find(Auth::user()->id);
// get tags relation
$userTags = $user->tag->toArray();
// select photos based on user tags
$photos = Photo::whereHas('tag', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tag->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
When i pass i get an error
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
than i tried to use array_flatten() to clean my array
// get the logged in user
$user = $this->user->find(Auth::user()->id);
// get tags relation
$userTags =array_flatten($user->tag->toArray());
// select photos based on user tags
$photos = Photo::whereHas('tag', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tag->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
This way it works but not returning the correct tags.
Could please someone could lend me a hand on this?
Sure thing and I'll make a couple recommendations.
To get the user model, you simply have to use $user = Auth::user().
To use whereIn(), it's expecting a 1 dimensional array of user id's. The toArray() function is going to return an array of associative arrays containing all the users and their properties, so it's not going to work quite right. To get what you need, you should use lists('id').
And one last thing that has really helped me is when you are setting up a relation that's going to return a collection of objects (hasMany, belongsToMany()), make the relation name plurual, so in this case you would modify your tag() function to tags().
So with all that in mind, this should work for you.
// get the logged in user
$user = Auth::user();
// get tags relation
$userTags = $user->tags()->lists('id');
// select photos based on user tags
$photos = Photo::whereHas('tags', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tags->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
And I'd suggest to modify your relation to... though not hugely important.
public function tags()
{
return $this->belongsToMany('Tag', 'users_tag');
}

How can I query raw via Eloquent?

I am trying to do a query in my Laravel app and I want to use a normal structure for my query. This class either does use Eloquent so I need to find something to do a query totally raw.
Might be something like Model::query($query);. Only that doesn't work.
You may try this:
// query can't be select * from table where
Model::select(DB::raw('query'))->get();
An Example:
Model::select(DB::raw('query'))
->whereNull('deleted_at')
->orderBy('id')
->get();
Also, you may use something like this (Using Query Builder):
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Also, you may try something like this (Using Query Builder):
$users = DB::select('select * from users where id = ?', array(1));
$users = DB::select( DB::raw("select * from users where username = :username"), array('username' => Input::get("username")));
Check more about Raw-Expressions on Laravel website.
You can use hydrate() function to convert your array to the Eloquent models, which Laravel itself internally uses to convert the query results to the models. It's not mentioned in the docs as far as I know.
Below code is equviolent to $userModels = User::where('id', '>', $userId)->get();:
$userData = DB::select('SELECT * FROM users WHERE id > ?', [$userId]);
$userModels = User::hydrate($userData);
hydrate() function is defined in \Illuminate\Database\Eloquent\Builder as:
/**
* Create a collection of models from plain arrays.
*
* #param array $items
* #return \Illuminate\Database\Eloquent\Collection
*/
public function hydrate(array $items) {}
use DB::statement('your raw query here'). Hope this helps.
I don't think you can by default. I've extended Eloquent and added the following method.
/**
* Creates models from the raw results (it does not check the fillable attributes and so on)
* #param array $rawResult
* #return Collection
*/
public static function modelsFromRawResults($rawResult = [])
{
$objects = [];
foreach($rawResult as $result)
{
$object = new static();
$object->setRawAttributes((array)$result, true);
$objects[] = $object;
}
return new Collection($objects);
}
You can then do something like this:
class User extends Elegant { // Elegant is my extension of Eloquent
public static function getWithSuperFancyQuery()
{
$result = DB::raw('super fancy query here, make sure you have the correct columns');
return static::modelsFromRawResults($result);
}
}
Old question, already answered, I know.
However, nobody seems to mention the Expression class.
Granted, this might not fix your problem because your question leaves it ambiguous as to where in the SQL the Raw condition needs to be included (is it in the SELECT statement or in the WHERE statement?). However, this piece of information you might find useful regardless.
Include the following class in your Model file:
use Illuminate\Database\Query\Expression;
Then inside the Model class define a new variable
protected $select_cols = [
'id', 'name', 'foo', 'bar',
Expression ('(select count(1) from sub_table where sub_table.x = top_table.x) as my_raw_col'), 'blah'
]
And add a scope:
public function scopeMyFind ($builder, $id) {
return parent::find ($id, $this->select_cols);
}
Then from your controller or logic-file, you simply call:
$rec = MyModel::myFind(1);
dd ($rec->id, $rec->blah, $rec->my_raw_col);
Happy days.
(Works in Laravel framework 5.5)
use Eloquent Model related to the query you're working on.
and do something like this:
$contactus = ContactUS::select('*')
->whereRaw('id IN (SELECT min(id) FROM users GROUP BY email)')
->orderByDesc('created_at')
->get();
You could shorten your result handling by writing
$objects = new Collection(array_map(function($entry) {
return (new static())->setRawAttributes((array) $entry, true);
}, $result));
if you want to select info it is DB::select(Statement goes here) just remember that some queries wont work unless you go to Config/Database.php and set connections = mysql make sure 'strict' = false
Just know that it can cause some security concerns
if ever you might also need this.
orderByRaw() function for your order by.
Like
WodSection::orderBy('score_type')
->orderByRaw('FIELD(score_type,"score_type") DESC')
->get();

Categories