I have 2 tables
student_job_log->id,job_id,student_id,created_dt
student_info->id,user_id,first_name,last_name
I have made the relations in model(studentJobLog)
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'student_info'=>array(self::BELONGS_TO,'StudentInfo','id','joinType'=>'LEFT JOIN',
'select'=>'first_name, last_name')),
);
}
I got the error in this
what is the problem.
something is wrong in my relations that i dont know :(
I want the first_name and last_name from student_info plz help me...:(
Foreign key must be the one from you current model that is mapped to the StudentInfo
return array(
'student_info'=>array(self::BELONGS_TO,'StudentInfo','student_id',),
);
now use it like
echo $job->student_info->first_name . ', ' . $job->student_info->last_name;
Related
I have a problem with Laravel 7 Eloquent. I have 2 tables joined by many to many relation. Table user is connected to PaymentModule by pivot table PaymentModuleUser. I need to use where on pivot table on statement is_active = 1. When i use toSQL() in my model SQL returns good results but when i check my Eloquent Query in Controller, data that i revicive ignore my wherePivot method (return all data from table ignoring is_active = 1 field subscribers = null and get me this user.. I must do it if my pivotWhere = null dont show this user). Could you point me where i get wrong with my code?
My UserTable model:
public function subscriber(){
return $this->belongsToMany(PaymentsModule::class, 'payment_module_user', 'user_id')->withPivot('is_active');
}
MyController:
$users = User::with(['subscriber'=>function($query)
{
$query->wherePivot('is_active','=', 1);
}])->get();
print_r($users);
Try with
$users = User::with('subscriber' => function($query) {
$query->where('payment_module_user.is_active', 1);
})->get();
print_r($users);
The pivot table is already joined by eloquent, so just start using it
Found it here.
In your controller, try using this
$query->wherePivot('is_active', 1);
Instead of,
$query->wherePivot('is_active','=', 1);
I have three tables. I want to display all data from cms_planner table together with Topic Name from cms_topic table. To achieve that, I need to go through the cms_subject table.
I want to use belongsToMany but I already have cms_subject table that holds the foreign key for cms_planner and the foreign key for cms_topic. The table name does not represent pivot key.
I also want to use hasManyThrough but it doesn't work. I'm thinking to inverse the hasManyThrough.
How can I achieve that?
1. CmsPlanner
i. planner_id
ii. subject_id
iii. date_start
2. CmsSubject
i. subject_id
ii. topic_id
3. CmsTopic
i. topic_id
ii. topic name
In CmsPlanner model
public function subject(){
return $this->hasManyThrough(
'App\CmsTopic',
'App\CmsSubject',
'topic_id', 'topic_id', 'planner_id');}
In CmsPlanner controller
CmsPlanner::with('subject')->get();
Add this relation on CmsSubject
public function cmsTopic()
{
return $this->belongsTo('App\Models\CmsTopic', 'topic_id', 'topic_id');
}
then add following relation on CmsPlanner
public function cmsSubject()
{
return $this->belongsTo('App\Models\CmsSubject', 'subject_id', 'subject_id');
}
to get data
$cms_planner = CmsPlanner::with('CmsSubject')->where('id', $planner_id)->get();
'user' => $this->business->user
I have the database just like this
==== cis_policy_registration====
id
policy_id
email_id
policy_start_date
==== cis_policy_family_details===
id
policy_id
is_main_applicant
firstname
lastname
gender
Now how to make the relation between models with the policy_id (both tables),
I want to take firstname and lastname in registration model and check is main applicant
that must list in CGridView
who can solve this problem
thanks in advance
The relation between these two tables should be handled from the "main" model (Policy), so in Policy model class you should have:
'policy_reg' => array(self::HAS_ONE, 'PolicyRegistration', 'policy_id'),
'policy_details' => array(self::HAS_ONE, 'PolicyDetails', 'policy_id'),
And then:
$policy = Policy::model()->with(array('policy_details'))->findByPk($pk);
$policy->policy_details->is_main_applicant;
...
And in CGridView you can print the relational value like this (after sending CActiveDataProvider object from Policy model):
'policy_details.firstname'
or
array(
'name'=>'Firstname',
'value'=>'$data->policy_details->firstname',
),
I'd like to set up a CGridView. I'm looking to display data from 2 different tables in one view. The data is from a table called student, and another table called employee.
employee is refereed by student(reg_no)
student table
reg_no (primary key)
s_name
dept
f_name
employee table
e_no(primary key)
e_name
desig
salary
reg_no(foreign key)
I want to display the (reg_no,s_name,f_name) from student and (design,salary) from employee table in a single grid view, can anyone please give an idea or any tutorial,
First make sure that your models and relationships are defined properly. Check the models to make sure that relationships are there.
e.g. you shall have an entry like this in your employee model;
function relations() {
return array(
'reg_no'=>array( self::BELONGS_TO, 'Student', 'reg_no' ),
);
}
Use CActiveDataProvider in the CGridView instead of an array as the data source.
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->searchEmplyees(),
.......
.......
Add another search cirteria to your model that returns the data as a CActiveDataProvider.
public function seachEmployees()
{
$criteria=new CDbCriteria;
$criteria->alias = 'i';
$criteria->compare('id',$this->id);
.......
.......
$criteria->join= 'JOIN 'your table name' d ON (i.id=d.id)';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'order_in_sna ASC',
),
));
}
I have just typed this code in for your reference so you understand how Yii is handling all of this for you. This is another good example, again from the Yii Framework site.
I have an entity called Books that can have a list of more books called RelatedBooks.
The abbreviated Book entity looks something likes this:
public class Book
{
public virtual long Id { get; private set; }
public virtual IList<Book> RelatedBooks { get; set; }
}
Here is what the mapping looks like for this relationship
HasManyToMany(x => x.RelatedBooks)
.ParentKeyColumn("BookId")
.ChildKeyColumn("RelatedBookId")
.Table("RelatedBooks")
.Cascade.SaveUpdate();
Here is a sample of the data that is then generated in the RelatedBooks table:
BookId RelatedBookId
1 2
1 3
The problem happens when I Try to delete a book. If I delete the book that has an ID of 1, everything works ok and the RelatedBooks table has the two corresponding records removed. However if I try to delete the book with an ID of 3, I get the error "The DELETE statement conflicted with the REFERENCE constraint "FK5B54405174BAB605". The conflict occurred in database "Test", table "dbo.RelatedBooks", column 'RelatedBookId'".
Basically what is happening is the Book cannot be deleted because the record in the RelatedBooks table that has a RelatedBookId of 3 is never deleted.
How do I get that record to be deleted when I delete a book?
EDIT
After changing the Cascade from SaveUpdate() to All(), the same problem still exists if I try to delete the Book with an ID of 3. Also with Cascade set to All(), if delete the Book with and ID of 1, then all 3 books (ID's: 1, 2 and 3) are deleted so that won't work either.
Looking at the SQL that is executed when the Book.Delete() method is called when I delete the Book with an ID of 3, it looks like the SELECT statement is looking at the wrong column (which I assume means that the SQL DELETE statment would make the same mistake, therefore never removing that record). Here is the SQL for the RelatedBook
SELECT relatedboo0_.BookId as BookId3_
, relatedboo0_.RelatedBookId as RelatedB2_3_
, book1_.Id as Id14_0_
FROM RelatedBooks relatedboo0_
left outer join [Book] book1_ on relatedboo0_.RelatedBookId=book1_.Id
WHERE relatedboo0_.BookId=3
The WHERE statment should look something like this for thie particular case:
WHERE relatedboo0_.RelatedBookId = 3
SOLUTION
Here is what I had to do to get it working for all cases
Mapping:
HasManyToMany(x => x.RelatedBooks)
.ParentKeyColumn("BookId")
.ChildKeyColumn("RelatedBookId")
.Table("RelatedBooks");
Code:
var book = currentSession.Get<Book>(bookId);
if (book != null)
{
//Remove all of the Related Books
book.RelatedBooks.Clear();
//Get all other books that have this book as a related book
var booksWithRelated = currentSession.CreateCriteria<Book>()
.CreateAlias("RelatedBooks", "br")
.Add(Restrictions.Eq("br.Id", book.Id))
.List<Book>();
//Remove this book as a Related Book for all other Books
foreach (var tempBook in booksWithRelated)
{
tempBook.RelatedBooks.Remove(book);
tempBook.Save();
}
//Delete the book
book.Delete();
}
Rather than setting the cascade attribute, I think you need to simply empty the RelatedBooks collection before deleting a book.
book.RelatedBooks.Clear();
session.Delete(book);
Cascading deletes is not typically done in a many-to-many relationship because it will delete the object at the other end of the relationship, in this case a Book.
This just got updated:
http://fluentnhibernate.lighthouseapp.com/projects/33236/tickets/115-self-referencing-relationships