Cannot get relation in Laravel pivot tables - php

I want to build relations between three tables in laravel. Currently i have three models
Classroom,
public function subjects(){
return $this->belongstoMany('Subject','subject_section_classroom');
}
Section,
Subject
My Tables are
classrooms(id, name)
sections(id, name)
subjects(id, name)
subject_section_classroom( id, classroom_id, section_id, subject_id)
In my classroomsController I have
public function assignsubjects($class_id, $section_id){
$classroom = Classroom::find($class_id);
$section = Section::find($section_id);
$subjects = Subject::lists('name','id');
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
$subjects = Subject::lists('name','id');
return view('assignedit', compact('classroom','section','subjects', 'selected_subjects'));
}
But I can't get the selected_subjects from above relation. And when I tried to get the sql of the above query (with ->toSQL()), I get
`"select * from `myschool_subjects` inner join `myschool_subject_section_classroom` on `myschool_subjects`.`id` = `myschool_subject_section_classroom`.`subject_id` where `myschool_subject_section_classroom`.`classroom_id` = ? and `section_id` = ?"`
I can't figure what I am doing wrong here.
Please Help.

I think your problem is coming from
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
Change it to:
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1)->get();

Related

how to order by column of related table in laravel eloquent?

I have two table and their models named Attendance and Line,
I am trying to get all from 'attendances' which is group by line_id and order by line names
here is a portion of what I have tried
public function lineWiseReport(Attendance $attendance){
$repository = $this->repository;
if(Input::has('date')){
$date = Input::get('date');
$attn->where('date','like','%'.$date.'%');
$attendances = $attn
->where('employee_type_id',2)
->orderBy('lines.name', 'ASC') //how to do this?
->get()->groupBy('line_id');
}else{
$date = '';
$attendances = [];
}
}
class Attendance extends Model
{
public function line()
{
return $this->belongsTo(Line::class);
}
}
Now I get only group by line_id but I want it to be sorted like Line A, Line B, Line C in a ascending order.
You have to join with the lines table before you can use values from that table.
$attendances = $attn
->join('lines', 'lines.id', '=', 'line_id')
->where('employee_type_id', 2)
->orderBy('lines.name', 'ASC') //how to do this?
->get()
->groupBy('line_id');
This might however return more records if a model contains more lines.

Laravel table joins

I'm trying to do some table joins and having some trouble.i need to display
the customer’s complete name and title, item description, quantity ordered, for each item ordered after April 2000. i made a SQL script that works but i need to use Laravel ORM.
SELECT `first_name`,`last_name`,o.order_id,`quantity`,`description`,`date_placed`
FROM `customer` c
JOIN `order` o
ON c.`customer_id` = o. `customer_id`
JOIN `orderline` ol
ON o.`order_id` = ol. `order_id`
JOIN `item` i
ON ol.`item_id` = i. `item_id`
WHERE `date_placed` > '2000-4-00';
I created 2 models for the tables "Customer", "Order"
here is my Customer model
public function orders(){
return $this->hasMany('App\Order','customer_id');
}
here is my order model
public function orderline(){
return $this->hasMany('App\Orderline','order_id');
}
right now i am able to get some of my data but i dont feel like this is a good way to go about
$customer = Customer::all();
foreach($customer as $input){
$item = Customer::find($input->customer_id)->orders;
$name = $input->title . ' ' . $input->first_name . ' ' . $input->last_name;
$datePlaced = null;
$orderID = null;
foreach($item as $value){
$orderID = $value->order_id;
$datePlaced = $value->date_placed;
$order = Order::find($value->order_id)->orderline;
}
if anyone could point me in the right direction that would be great.
It looks like you want to get all Customers with their Orders and OrderLines?
Customer::with(['order' => function ($query) {
$query->where('date_placed', '>=', '2000-04-01')->with('orderline');
}])->get();
If you want to limit the columns on the relationships, you can...
Customer::with(['order' => function ($query) {
$query->select(/* columns */)->where('date_placed', '>=', '2000-04-01')
->with(['orderline' => function ($query) {
$query->select(/* columns here */);
}]);
}])->get();
Just make sure if you specify the columns in the relationships, that you're selecting all of the foreign keys or related columns for each relationship.

How to fetch data with pivot table using where condition on pivot in laravel4

How can I fetch data with belongsToMany relation models.
Table tags
- id
- name
...
Table photo_entries
- id
...
Table photo_entry_tag
- id
- tag_id
- photo_entry_id
Tag.php
public function photo_entry()
{
return $this->belongsToMany('PhotoEntry');
}
PhotoEntry.php
public function tags()
{
return $this->belongsToMany('Tag');
}
Now I need to fetch photo entries from photo_entries table with their tags where tag_id=1.
I have tried this:
$photos = PhotoEntry::orderBy('votes', 'desc')->with(array('tags' => function($query)
{
$query->where('tag_id', 1);
}))->paginate(50);
But its not giving me the proper result, its returning all photos. I am not getting what is the issue.
Can any one please help me.
You need to select all records form photo_entries table that has a relation in photo_entry_tag table so to do that your query should be like this
$tag_id = 1;
$query = "SELECT * FROM `photo_entries` WHERE `id` IN (SELECT `photo_entry_id` FROM `photo_entry_tag` WHERE `tag_id` = {$tag_id})";
Also the equivalence code in eloquent will be like the code below
$tag_id = 1;
$photos = PhotoEntry::whereIn('id', function($query) use ($tag_id) {
$query->select('photo_entry_id')->from('photo_entry_tag')->whereTagId($tag_id
);
})->get();
Also you can add orderBy('votes', 'desc') just before get() to sort the result

Codeigniter Many to Many Error

I have 3 tables ...
instructors, classes and instructor_teach
I want to display a list of classes that the instructor teaches
I have been using tutorials and the like to try and work this out so if my code is messy i do apologize.
Model...
function getMemberPrograms($id){
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
return;
}
In the controller i just have a print_r statement to see what the results are but at the moment i am getting
Error Number: 1066
Table/alias: 'instructor_teach' non unique
SELECT * FROM (`instructor_teach`, `classes`) JOIN `instructor_teach`
ON `instructors`.`id` = `instructor_teach`.`instructor_id` JOIN
`classes` ON `instructor_teach`.`program_id` = `classes`.`id` WHERE
`instructor_teach`.`instructors_id` = '1'
Filename: C:/wamp/www/fitness/application/models/members_model.php
Line Number: 16
what i want is an array that has all the information from the classes the instructor teaches so
instructor 1 teaches class 1, class 2
array would return
class 1.name
class 1.description
class 2.name
class 2.description
etc..
I hope this makes sense as i am still getting to terms with this
Many Thanks
Joe
I think you are joining the table instructor_teach to it self instructor_teach
take a look:
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
I think it should be:
$this->db->from('instructor_teach');
$this->db->join('instructors', 'instructors.id = instructor_teach.instructor_id');
:)
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
First is you select to table instructor_teach then afterwards you want to join it again with table instructor_teach where in it will give you a error.
And one thing also if you can select only important columns from each tables is much more okay.
I think the query should look like this
$this->db->select('*');
$this->db->from('instructors');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
i don't know if this correct, but try to change the first join with instructor table
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
to
$this->db->join('instructor', 'instructors.id = instructor_teach.instructor_id');
try this
function getMemberPrograms($id){
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
return true;
}

ZF2 multiple tables join in one model, get columns from join table

So here is my query:
public function fetchAd($adID){
$row = $this->tableGateway->select(function(Select $select) use ($adID){
$select->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$select->where(array('ads.adID' => $adID));
});
return $row->current();
}
So what I'm doing I'm querying the ad table and join the adDetails table in order for me to get the details for a certain AD, the problem is that the entity AD which belongs to the model that I'm doing the query, it doesn't have the columns names(variables) from the adDetails table; so it will only return the columns from the AD table, because the entity doesn't have those fields in the exchangeArray()
I have tried to extend the AD entity to use the AdDetails entity but it returns now to object array but with the fields as null, because it can;t populate them.
So, how should I do this, in order for me to have all the columns available in the model for the tables that will join?
I'm planning to join other tables as well.
Ok I solved the problem, the thing is that it will return an array, and it won't use the ORM style, but it does the job, for now relations are not supported in ZF2 like in ZF1;
use Zend\Db\Sql\Sql,
Zend\Db\Sql\Where;
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from($this->tableGateway->table)
->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$where = new Where();
$where->equalTo('ads.adID', $adID) ;
$select->where($where);
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
return $result->current();
public function fetchJoin()
{
$select = new \Zend\Db\Sql\Select;
$select->from('tablea a');
$select->columns(array('*'));
$select->join('tableb b', "b.id = a.b_id", array('field1'), 'left');
// to display query string remove comment in next line
//echo $select->getSqlString();
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}

Categories