Sorry for the question title but I can't really find an suitible title.
I use Laravel 3 with Eloquent models (first project in Laravel).
I have an user, list and item model. The user can't fetch any lists, the list can fetch items. But the user can order the items, so the order is saved per user/item.
Will be more clear with following data (simplified for clarity):
Database table:
USER
--------
id
name
LIST
-------
id
name
ITEM
-------
id
list_id
name
USER_ITEM_ORDER
---------------
user_id
item_id
order
List model:
class List extends Eloquent {
public function items() {
return $this->has_many('Item');
}
}
Now I want to use the list model to get all the items based on an user, $list->items($user_id) --> array with items with the user's order.
Can someone show me the way to achieve this?
Please try using this code :
public static function NAMEUserId() {
$query = DB::table('username')
->select(array('users.username', DB::raw('NAME(user's.id) as UserID')))
->join('users', 'items.user_id', '=', 'users.id')
->group_by('users.id')
->order_by('usersid', 'desc')
->get();
return $query;
}
Yeah! I fixed it. :D I'll answer my own question because there is an up vote..
It was pretty easy, just use Fluent on the returned object like this:
public function items($user_id = 0) {
$items = $this->has_many('Item');
// do we need to get the order?
if($user_id != 0) {
$items = $items->left_join('user_item_order', 'items.id', '=', 'user_item_order.item_id')
->where('user_item_order.user_id', '=', $user_id)
->order_by('user_item_order.order', 'asc');
}
return $items->get();
}
Related
This is my first post. I am in a trouble in my laravel project
Here is my data table.
I have student Id like 1,2,3. every students have multiple results followed by courses.
I need to arrange them like that
I tried groupby and got this result
Is there any possible way to arrange them according to students.
Thank You
code: controller:
public function notification()
{
$auth_id = Auth::user()->id;
$teacher = Teacher::where('user_id', $auth_id)->first();
$teacher_id = ($teacher->id);
$batch = Batch::where('teacher_id', $teacher_id)->first();
$courses = AssignCourses::with('course')
->where('semester_id', $batch->semester_id)
->get();
$current_semester_results = Result::with(['student', 'course'])
->where('semester_id', $batch->semester_id)
->get()
->groupBy('student.id');
$batch_students = Student::with('result')
->where('semester_id', $batch->semester_id)
->get();
return view('users.teacher.my_batch.notification', compact(['current_semester_results', 'courses', 'batch_students']));
}
Just use the $batch_students and apply any aggregations on your PHP code, it is easier to do it.
$batch_students = Student::with('result')
->where('semester_id', $batch->semester_id)
->get();
$batch_students_grouped = $batch_students->groupBy('result.student_id');
Note: I could not test since I don't have the tables, so you might need to change the student_id nest/access index in the last line of code.
you can print out your $batch_students_grouped->all() and see how you should iterate your data and show it in frontend.
I have the code below to get all of my messages from my database. All messages contain a room_ID. I want to have the most recent 20 messages of each room when I go to localhost:8000/api/messages. Is it possible and how?
public function showAll()
{
$messages = Message::all();
foreach ($messages as $message) {
$message->user;
$message->room;
}
return response()->json($messages);
}
What you need is this:
https://laravel.com/docs/5.7/pagination
Flat and simple, you would just do this for each of the rooms:
$messages = Message::where('room_id', $room->id)->orderBy('date_column')
->paginate(20)->get();
This ofcourse can be simplified if you setup your relations properly.
I have 3 models Job, Diary, Resource.
Jobs has relation with Diary and Diary has relation with Resource.
I wanted to get all Resource associated with a Job and did this using
public function labourers()
{
return $this->hasManyThrough(Resource::class, Diary::class, 'job_id');
}
On my Job class.
Now I want to group the results by User who's user_id is a column in Resource and then show the total hours.
This is the closest I can get.
$job = Job::where('job_number', 3007)->first();
$labour = $job->labourers()->get();
$results = $labour->groupBy('user_id');
echo $results;
foreach($results as $result)
{
$hours = $result->sum('hours');
echo $result[0]->user_id." - ";
echo $hours.". ";
}
This gets me the user_id and the sum of the hours but I am unable to access the user name through the relationship set up on the resource model
public function user()
{
return $this->belongsTo(User::class);
}
with
$result->user->name;
This produces
Property [user] does not exist on this collection instance.
How can I return a collection which allows me to access the users name and the sum of the hours.
The reason you're not able to access the user like that is because (in this case) groupBy is a method on the collection that returns another collection.
Firstly, eager load the user relationship on so that your code is a bit more efficient:
$labour = $job->labourers()->with('user')->get();
Secondly, since you have a collection you can use first() instead of [0]:
$result->first()->user_id
Lastly, you would have to access the user in the same way you're accessing the user_id:
$result->first()->user
So, you would end up with something like:
$job = Job::where('job_number', 3007)->first();
$labourers = $job->labourers()->with('user')->get();
$results = $labourers->groupBy('user_id');
foreach($results as $result)
{
echo $result->first()->user->name . ' - ' . $result->sum('hours') . '.';
}
You can try this
$job = Job::where('job_number', 3007)->with(['labourers' => function($query){
$query->select('id','user_id', DB::raw('sum(hours) as hours'))->groupBy('user_id');
}, labourers.user])->first();
$results = $job->labourers;
foreach($results as $result){
print_r($result->user);
print_r($result->hours);
}
I want to get Shop data and also associated Comments with this Shop, but Comments contains also author_id which connected to Authors table.
How to get also not only Comments, but also and Authors data by author_id?
Its my Shops controller:
public function viewShop($slug = null)
{
$shop = $this->Shops->find('all')
->where(['slug'=>$slug])
->contain(['Comments']);
$this->set('shop', $shop);
$this->render('index');
}
First bind your Comment model with Author model as BelongsTo and then replace your code with this.
public function viewShop($slug = null)
{
$shop = $this->Shops->find('all')
->where(['slug'=>$slug])
->contain(array('Comment'=>array("Author")));
$this->set('shop', $shop);
$this->render('index');
}
I have a form that collects the CustomerName, Period and UnitOfMeasure[buom].
I then pass this information to my controller which puts the post data into an array and passes it to the view.
This controller works 100% currently.
function new_blank_order_lines()
{
if($this->input->post()){
$data = array(
'customer' =>$this->input->post('customer'),
'period' =>$this->input->post('period'),
'buom' =>$this->input->post('buom')
);
$this->session->set_userdata($data);
$this->Sales_model->get_creditlimit($this->input->post('customer'));
}
$this->load->view('sales/new_blank_order_lines',$this->session->all_userdata());
}
else {
redirect('/sales/permError');
}
}
What I want to do is query the customers credit limit AND credit balance using the customer post value and pass it to my view to use in the next form.
so my model is:
function get_creditlimit($customer)
{
$this->db->select('creditlimit','creditbalance');
$this->db->from('Customers');
$this->db->where('Customername',$customer);
$q = $this->db->get();
if($q->num_rows() > 0)
{
return $q->result();
}
}
So in my controller I am calling the model function with:
$this->Sales_model->get_creditlimit($this->input->post('customer'));
here I am passing the customer post value to the model to fetch the correct credit limit? is this correct?
My question is how do I pass the post information array to the view AND the credit limit information to the view.
Do I need to add the model result to the array and pass a single array? if so how do I do this?
Thanks as always,
Just add it to the $data array:
$data = array(
'customer' =>$this->input->post('customer'),
'period' =>$this->input->post('period'),
'buom' =>$this->input->post('buom'),
'creditLimit' => $this->Sales_model->get_creditlimit($this->input->post('customer'))
);