Hello i have 2 tables Student & Faculty
i want to call them to my index(view), So I figured how to join them. but I have a problem, I need to divide these 2 tables into a category but I don't know the code. Can someone please help me?
public function getStudentReguler()
{
return $this->db->table('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', *i want to be like, where categor = A*)
->get()->getResultArray();
}
thank you
public function getStudentReguler()
{
return $this->db->table('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', 'A')
->get()->getResultArray();
}
Please try this:
$this->db->select('*')
->from('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', 'A')
->get()->getResultArray();
Related
I have a one to many relation between Person and Visit tables like this:
public function visits()
{
return $this->hasMany('App\Models\Visit');
}
And want to get the persons who has a sickness_id of 1 in the relation like this:
$persons = Person::whereHas('visits', function ($query) {
$query->where('sickness_id', 1);
})->get();
And it works fine but I want to search just last visit of each person.
I mean if a person has two visits, one with sickness_id of 1 and other with sickness_id of 2, do not return this person because last visit is sickness_id of 2.
you can use hasOne relation for that:
public function lastVisit()
{
return $this->hasOne('App\Models\Visit')->latest();
}
then you can load it:
$persons = Person::whereHas('lastVisit', function ($query) {
$query->where('sickness_id', 1);
})->get();
I think the above answer is gonna work. Using addSelect, this might also work:
Person::addSelect('last_visit_id', Visit::select('id')
->whereColumn('person_id', 'persons.id')
->latest()
->limit(1)
)
->where('last_visit_id', 1)
->get();
$person = modelname::query()
->where(['sickness_id' => '1' ])
->select('visits')
->orderBy('id', 'DESC')
->first();
I tried to fetch data using joins and the data is repeating,
The controller code is:
public function searchjobs2()
{
//$id=$_SESSION['id'];
$lan = $_POST["picke"]; //var_dump($id);die();
$value['list']=$this->Free_model->get_jobs($lan);//var_dump($value);die();
$this->load->view('free/header');
$this->load->view('free/searchjobs2',$value);
}
And the model:
public function get_jobs($lan)
{
$this->db->select('*');
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work.login_id = tbl_work_stats.login_id",'inner');
$this->db->where("language LIKE '%$lan%'");
// $this->db->where('tbl_work_stats.login_id',$id);
$this->db->order_by('insertdate','asc');
$query=$this->db->get()->result_array();//var_dump($query);die();
return $query;
}
I have used
foreach ($list as $row){
...
}
for listing.
Using distinct will remove duplicate fields:
$this->db->distinct();
From what I can see, your query has ambiguity, and an error in the join statement, also your where like is part of the problem, I would recommend trying this even do there are some missing info, find out wich field you need to join from the second table.
public function get_jobs($lan){
$this->db->select("tbl_work_stats.*, tbl_work.fields");
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work_stats.login_id = tbl_work.login_id","inner");
$this->db->where("tbl_work.language LIKE", "%" . $lan . "%" );
$this->db->order_by("tbl_work_stats.insertdate","asc");
$query=$this->db->get()->result_array();
return $query;}
do you mean to join on login_id?
I am guessing that is the user logging in and it is the same for many entries of tbl_work_stats and tbl_work.
you didn't post your schema, , but login_id doesn't seem like right thing to join on. how about something like tbl_work.id = tbl_work_stats.tbl_work_id or similar?
also CI $db returns self, so you can do:
public function get_jobs(string $lan):array
{
return $this->db->select()
->from('tbl_work_stats')
->join('tbl_work','tbl_work.id = tbl_work_stats.work_id')
->like('language',$lan)
->order_by('insertdate')
->get()
->result_array();
}
In Laravel we can setup relationships like so:
class User {
public function items()
{
return $this->belongsToMany('Item');
}
}
Allowing us to to get all items in a pivot table for a user:
Auth::user()->items();
However what if I want to get the opposite of that. And get all items the user DOES NOT have yet. So NOT in the pivot table.
Is there a simple way to do this?
Looking at the source code of the class Illuminate\Database\Eloquent\Builder, we have two methods in Laravel that does this: whereDoesntHave (opposite of whereHas) and doesntHave (opposite of has)
// SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id AND id = 1) < 1) AND ...
User::whereDoesntHave('Role', function ($query) use($id) {
$query->whereId($id);
})
->get();
this works correctly for me!
For simple "Where not exists relationship", use this:
User::doesntHave('Role')->get();
Sorry, do not understand English. I used the google translator.
For simplicity and symmetry you could create a new method in the User model:
// User model
public function availableItems()
{
$ids = \DB::table('item_user')->where('user_id', '=', $this->id)->lists('user_id');
return \Item::whereNotIn('id', $ids)->get();
}
To use call:
Auth::user()->availableItems();
It's not that simple but usually the most efficient way is to use a subquery.
$items = Item::whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
})
->get();
If this was something I did often I would add it as a scope method to the Item model.
class Item extends Eloquent {
public function scopeWhereNotRelatedToUser($query, $user_id)
{
$query->whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
});
}
}
Then use that later like this.
$items = Item::whereNotRelatedToUser($user_id)->get();
How about left join?
Assuming the tables are users, items and item_user find all items not associated with the user 123:
DB::table('items')->leftJoin(
'item_user', function ($join) {
$join->on('items.id', '=', 'item_user.item_id')
->where('item_user.user_id', '=', 123);
})
->whereNull('item_user.item_id')
->get();
this should work for you
$someuser = Auth::user();
$someusers_items = $someuser->related()->lists('item_id');
$all_items = Item::all()->lists('id');
$someuser_doesnt_have_items = array_diff($all_items, $someusers_items);
Ended up writing a scope for this like so:
public function scopeAvail($query)
{
return $query->join('item_user', 'items.id', '<>', 'item_user.item_id')->where('item_user.user_id', Auth::user()->id);
}
And then call:
Items::avail()->get();
Works for now, but a bit messy. Would like to see something with a keyword like not:
Auth::user()->itemsNot();
Basically Eloquent is running the above query anyway, except with a = instead of a <>.
Maybe you can use:
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
Source: http://laravel.com/docs/4.2/queries#advanced-wheres
This code brings the items that have no relationship with the user.
$items = $this->item->whereDoesntHave('users')->get();
Shortly, there are teachers and i have to attach them courses. Every course should be added once only(not twice). My code is working but only for element with id=1.And the other courses can be attached to a teacher more than once. I am writing the code in laravel. (php).
I can't uderstand why it is working only for the first element(course($id=1)).
Can you help me please. Where is my mistake?? Thank You in advance.
Here is my code. To One Teacher, many different courses should be attached. But not one course twice!
public function addCourse($id, Request $request) {
$teacher = Teacher::findOrFail($id);
if($teacher->has('courses')->where('id', $request->get('course_id'))->get()->isEmpty()) {
$teacher->courses()->attach($request->get('course_id'));
}
else {
flash()->error('This Course has been added already!')->important();
}
return back();
}
I believe there is an issue in how you are querying.
When you do this...
$teacher->has('courses')->where('id', $request->get('course_id'))
That ->where() is still looking at the teachers table, not the courses table. I think what you really want to do is use a whereHas to determine if the teacher has that course.
$hasCourse = Teacher::whereHas('courses', function($q) use ($request) {
// Here we can add constraints on the courses table
$q->where('id', $request->get('course_id'));
})->where('id', $id)->exists();
if (! $hasCourse) {
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($id);
}
PROBLEM SOLVED. I used
$teacher->courses()->sync([$request->get('course_id')],$detaching =
false);
Finally i have this script:
> public function addCourse($id, Request $request) {
> $teacher = Teacher::findOrFail($id);
> $teacher->courses()->sync([$request->get('course_id')],$detaching =
> false);
>
> return back();
> }
Thank you all.
To attach a one to many
$teacher = Teacher::findOrFail($id);
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($teacher);;
$course->save();
Im trying to Joing 2 table in Fluent trough my Model i run the query on mysql client and give me the return i want.
this is the standard query
select `songlist`.*, `queuelist`.* from `songlist` inner join `queuelist` on `songlist`.`id` = `queuelist`.`songID` where `queuelist`.`songID` = songlist.ID and `songlist`.`songtype` = 'S' and `songlist`.`artist` <> "" order by `queuelist`.`sortID` ASC limit 4
it does return the data im looking for.
now on my model using fluent.
i did like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->join('queuelist', 'songlist.id', '=', 'queuelist.songID')
->select('songlist.*','queuelist.*')
->where('queuelist.songID', '=', 'songlist.ID')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}
and my controller to test if i get the data look like this
public function getComingUp()
{
$getcomingUp = Radio::comingUp();
foreach ($getcomingUp as $cup)
{
echo $cup->title;
}
// return View::make('comingup', compact('comingup'));
}
as you can see the foreach is no returning any data there is nothing wrong with the query because laravel give me no error at all. but i cant just get the foreach to display the data im looking for.
i try with $cup->songlist.title;
and it dont work ether.
Thanks any help will be appretiated. againg sorry for my English.
You can do something like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->select('songlist.*','queuelist.*')
->join('queuelist', 'queuelist.songID', '=', 'songlist.id')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}