In user:
public function posts()
{
return $this->hasMany(Post::class);
}
In post:
public function users()
{
return $this->belongsTo(Users::class);
}
I handle in controller:
$user = Users::find('1')->posts;
Then I get an array and the result returned is exactly what I need.
But when I query this way because I need to get a lot of data, the result is an empty array. What did I do wrong?
In UserController.php:
$listUser = Users::with('posts')
->select('name', 'title')
->where('type', 1)
->get(); // It returns posts as an empty array
Please give me any comments.
You have to select foreign key in posts:
$listUser = Users::select(['id', 'name'])
->with(['posts' => function($query) {
$query->select(['user_id','title']);
}])
->where('type', 1)
->get();
or
$result = User::select(['id', 'name'])
->with(['posts:user_id, title'])
->get();
Your relation is developed with a primary key and in your query you are missing the id to get the values.
$listUser = Users::with('posts')
->select('users.id', 'users.name', 'posts.title')
->where('posts.type', 1)
->get();
If you wish to select only some fields of the related model you can specify it in the with clause like the following. The select clause will work on the User query builder.
$listUser = Users::with('posts:user_id, title')
->select('name')
->where('type', 1)
->get();
Related
This is my select query with the inner join and the values that I want to select.
$user_reservation = DB::table('users')
->join('reservations', 'users.id', '=', 'reservations.users_id')
->select('users.id', 'reservations.id as res_id')
->get();
I need the res_id from the $user_reservation variable to be able to filter a result. Thank you
$reserved_rooms = $rr_model->where('reservation_id', '=', $user_reservation->res_id)->get();
It means you are receiving a collection, not an object because you are using ->get();. You need to loop through the collection.
foreach($user_reservation as $reservation) {
$reserved_rooms = $rr_model->where('reservation_id', '=', $reservation->res_id)->get();
}
But if you only want one instance of $user_reservation change your get() to first();
$user_reservation = DB::table('users')
->join('reservations', 'users.id', '=', 'reservations.users_id')
->select('users.id', 'reservations.id as res_id')
->first();
You can define the relationship in your models:
return $this->hasOne('App\User', 'foreign_key', 'local_key');
Define in your model
public function user()
{
return $this->hasOne('App\User');
}
or
public function user()
{
return $this->belongsTo('App\User');
}
Check the documentation:
https://laravel.com/docs/5.4/eloquent-relationships
I have another table called tableb and it has a user relationship defined through the user_id field.
I want to run a query against tableb where a certain date is within a certain range but then I want to grab the user table associated with that row but I only want it to grab the user if it's not been grabbed yet. I'm trying to do this all in 1 DB query. I have most of it done, but I'm having trouble with the unique part of it.
Here's what I have right now:
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->get();
So right now I have 3 entries in tableB from the same user, and ideally I'd like to only get 1 entry for that user.
How would I go about doing this?
Since you're selecting only users data, just add a groupBy clause in your query.
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get();
You should just add groupBy like this :
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get
Try This Code
App/user.php
public function getrelation(){
return $this->hasMany('App\tableB', 'user_id');
}
In Your Controller
Controller.php
use App/user;
public funtion filterByDate(user $user)
{
$date = '2016-02-01';
$result = $user->WhereHas('getrelation', function ($query) use($date) {
$query->whereDate('tableb.start_date', '>', $date)
->first();
});
}
i have two tables that share a relationship users and log table. I’m trying to query the users table and get the record from log with the highest id value
so far this is what I have that’s returning duplicate entries:
$students = User::with([
'course' => function ($query) {
$query->get(['id', 'name']);
}
])
->join('log', 'users.id', '=', 'log.user_id')
->where('log.event', 1)
->orderBy('log.id', 'desc')
->where('users.verified', 1)
->get(['users.*', 'log.id AS logid']);
Ideally, I want the last inserted record from the log table for each user
groupBy('user_id')
returns the first record
$students = User::with([
'course' => function ($query) {
$query->get(['id', 'name']);
}
])
->join('log', 'users.id', '=', 'log.user_id')
->where('log.event', 1)
->whereRaw('log.id = (select max(`id`) from log where `user_id` = users.id )')
->where('users.verified', 1)
->get(['users.*', 'log.id AS logid', 'log.user_id']);
I think you are very close to, only you need to use limit.
->where('users.verified', 1)
->take(1) // add this to get only a single record
->get(['users.*', 'log.id AS logid']);
Try the below solution with 1 more where condition without groupBy
$students = User::with([
'course' => function ($query) {
$query->get(['id', 'name']);
}
])
->join('log', 'users.id', '=', 'log.user_id')
->where('log.event', 1)
->orderBy('log.id', 'desc')
->where('users.verified', 1)
->where('log.id',DB::raw("SELECT MAX(id) FROM log WHERE log.user_id = users.id")) // get the max id value
->get(['users.*', 'log.id AS logid']);
I have two tables: a relationship table and a users table.
Relationship table looks like: 'user_one_id', 'user_two_id', 'status', 'action_user_id'.
Users table looks like: 'id', 'username'.
I would like to query the relationship table first and return an array of all the rows where the 'status' column = 0.
Then I would like to query the users table and return an array of ids and usernames where 'user_one_id' matches 'id'.
My code so far:
public function viewRequests()
{
$currentUser = JWTAuth::parseToken()->authenticate();
$friendRequests = DB::table('relationships')
->where('user_two_id', '=', $currentUser->id)
->where('status', '=', '0')
->get();
$requestWithUsername = DB::table('users')
->where('id', '=', $friendRequests->user_one_id)
->get();
return $requestWithUsername;
}
It's not working and I'm not sure what method is easiest to reach my desired output. How can I change these queries?
EDIT:
After reviewing the response, this is the working code:
$friendRequests = DB::table('users')
->select('users.id','users.username')
->join('relationships', 'relationships.user_one_id','=','users.id')
->where('relationships.status','=',0)
->where('relationships.user_two_id', '=', $currentUser->id)
->get();
Your SQL seems to be this:
SELECT id, username
FROM users
JOIN relationships
ON relationships.user_one_id = id
WHERE relationships.status = 0
Then the Laravel way:
DB::table('users')
->select('id','username')
->join('relationships', 'relationships.user_one_id','=','id')
->where('relationships.status','=',0)
->get();
IN Custom php code
$select_query = "select * from admin where Stutes = '1' order by ID asc";
How we can embed this code in my this laravel 5 code
public function index()
{
$books=Book::all();
return view('books.index', compact('books'));
}
You can use the Query builder
$admin= DB::tabe('admin')
->select("*")
->where("Stautes",1)
->orderBy("ID", "asc")
->get();
Optimised Query:
Since you are trying to retrieve all rows your query can be likewise:
$admin= DB::table('admin')->where("Status",1) ->orderBy("ID", "asc") ->get();
If you want to retrieve a specific column:
$admin_ids = DB::table('admin')->select('id')->where("Status",1) ->orderBy("ID", "asc") ->get();
Laravel Select docs
Hope this helpful.
In controller
public function index()
{
//$books=Book::all();
$books= DB::table('books')
->select('*')
->where('status', '1')
->orderBy('id', 'asc')
->get();
return view('books.index', compact('books'));
}