Insert data into pivot table in Laravel5.4 - mysql

I am working in Laravel5.4. I have created 3 table's.
User table :
tickets table :
ticket_cc_users table :
Now, I have create relation ship between users and tickets module like below.
User model :
public function tickets()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'ticket_id', 'user_id');
}
TicketController controller save method :
public function store(Request $request)
{
return $request->all();
$ticket = new Ticket;
$ticket->requester_id = $this->user['id'];
//$ticket->assignee_id = $request->assignee_id;
//$ticket->cc_id = $request->cc_id;
$ticket->type = $request->type;
$ticket->priority = $request->priority;
$ticket->subject = $request->subject;
$ticket->description = $request->description;
$ticket->status = $request->status;
if($request->link)
{
$ticket->link = $request->link;
$ticket->due_date = null;
}
if($request->due_date && $request->due_date !="")
{
$ticket->due_date = date('Y-m-d',strtotime($request->due_date));
$ticket->link = "";
}
if($ticket->save())
{
$ticket->users()->sync($request->cc_id);
foreach($request->ticket_tags as $value){
$tag = new Tag;
$tag->tag_name = $value['text'];
$tag->save();
$ticketTag = new TicketTag;
$ticketTag->tickets_id = $ticket->id;
$ticketTag->tags_id = $tag->id;
$ticketTag->save();
}
$data = Ticket::find($ticket->id);
Mail::to('khyati#infirays.com')->send(new CreateTicket($data));
$response = array(
'success' => true
);
}
return $response;
}
Here, I am going to store data into ticket table. So I need to store cc user data into ticket_cc_user table. So how can I store ticket_id and user_id into this table. Here, I can get multiple user_id. And I am using Eloquent ORM.
Here, It gives an error like SQLSTATE[42S22]: Column not found: 1054 Unknown column '$$hashKey' in 'field list' (SQL: insert into ticket_cc_users ($$hashKey, address, city_id, country_id, created_at, deleted_at, email, firstname, id, introducer_id, is_verified, lastname, phone, signature, state_id, ticket_id, updated_at, user_id, username, userrole_id) values (object:109, , , , 2017-02-10 05:26:01, , nisarg.b#infirays.com, , 26, 1, , , 9999999999, , , 1, 2017-02-14 08:33:18, 0, nisarg, 2))
So,what code should I have to change in save function to store data into ticket_cc_users table?

It seems that belongsToMany() parameters order should be changed. The first and the last(4-th) parameters should be "about" same instance.
UPDATE Also the body of tickets() and users() functions should be exchanged
So try this:
User model :
public function tickets()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'ticket_id', 'user_id');
}
From Laravel Many To Many Docs:
The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');

Related

Integrity constraint violation error when inserting data into a table that has a foreign Key

I have two tables in the database :
apartments table
id | user_id | Location
agents table
id | name | email | town
I have created a relationship between the two table in their respective models as below :
Apartment Model:
public function agent(){
return $this->belongsTo('App\Agent');
}
Agent Model :
public function apartments()
{
return $this->hasMany('App\Apartment');
}
When I fill in a form to post data into the apartments table I get this error :
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
(SQL: insert into apartments (user_id, Photo, Location, Size, Bedrooms, MasterBedrooms,
Unitdetails, Housedetails, Rent, updated_at, created_at) values (, 1497870161.jpg, Nairobi,
One bedroom, 1, 0, unit, house, 12000, 2017-06-19 11:02:42, 2017-06-19 11:02:42))
This is my controller :
class ApartmentController extends Controller
{
public function store(Request $request){
//Validating the data
$this->validate($request, array(
'Photo'=>'required|image',
'Location'=>'required|max:255',
'Size'=>'required',
'Bedrooms'=>'required',
'MasterBedrooms'=>'required',
'Unitdetails'=>'required',
'Housedetails'=>'required',
'Rent'=>'required',
));
//Store data into DB
$apartment = new Apartment;
$apartment->user_id = Auth()->id();
// $house->Photo = $request->Photo;
//Saving the photo
$image = $request->file('Photo');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(735, 460)->save($location);
$apartment->Photo = $filename;
$apartment->Location = $request->Location;
$apartment->Size = $request->Size;
$apartment->Bedrooms = $request->Bedrooms;
$apartment->MasterBedrooms = $request->MasterBedrooms;
$apartment->Unitdetails = $request->Unitdetails;
$apartment->Housedetails = $request->Housedetails;
$apartment->Rent = $request->Rent;
$apartment->save();
Session::flash('success', 'Sent successfully!');
return redirect::back();
}
}
This my migration to add foreign key to the apartments table:
public function up()
{
Schema::table('apartments', function (Blueprint $table) {
$table->integer('user_id')->after('id')->unsigned();
$table->foreign('user_id')->references('id')->on('agents');
});
}
The user_id in the apartments table should come from the agents table or should be the agent id in the agents table.
What I'm I missing?

Yii2 Not unique table/alias

i create a query like below but always error Not unique table/alias although i add alias for askPo in every relation model.
$query = AskPolicy::find();
$query-> JoinWith(['askPos'])
->where(['askPolicy.id' => 'askPos.id_policy'])
->innerJoinWith(['askPos.askGoods'])
->andWhere('ask_po.id = ask_goods.id_po')
->innerJoinWith(['askTransports'])
->andWhere('ask_policy.id = ask_transport.id_po')
->innerJoinWith(['client'])->andWhere(['id_client'=>Yii::$app->user->identity->id_client])->all();
below i have add alias
model a :
public function getAskPos()
{
return $this->hasMany(\frontend\modules\ask_marine_cargo\models\AskPo::className(), ['id_policy' => 'id'])->from(AskPo::tableName() . ' askPo1');;
}
model b :
public function getPo()
{
return $this->hasOne(\frontend\modules\ask_marine_cargo\models\AskPo::className(), ['id' => 'id_po'])->from(AskPo::tableName() . ' getPo');
}
SQL query :
SELECT
ask_goods.name,
ask_po.po_num,
ask_policy.policy_num,
ask_transport.type_transport
FROM ask_policy
INNER JOIN ask_po
ON ask_po.id_policy = ask_policy.id
INNER JOIN ask_goods
ON ask_po.id = ask_goods.id_po
INNER JOIN ask_transport
ON ask_policy.id = ask_transport.id_po;

Yii2 query for users in group

I had a DB that had a user table and a group table and the group table had a column user_id which made it simply to return a list of users in a group:
$users = User::find()
->where(['{{user}}.group_id' => $group_id])
->all();
Now the user_id column is gone and there is a third table group_user with user_id and group_id columns for the relationship.
I tried this:
$users = User::find()
->innerJoinWith('group_user)
->where(['{{group_user}}.group_id' => $group_id])
but received this error:
User has no relation named "group_user"
But I set the relationship in the User model:
public function getGroupUser() {
return $this->hasOne(GroupUser::className(), ['user_id' => 'id']);
}
What am I missing? This is used in a Humhub API.
I would reprogram your getGroupUser (renaming it to getGroups) relation using viaTable:
public function getGroups() {
return $this->hasMany(Group::className(), ['user_group.id_group' => 'group.id'])
->viaTable('user_group', ['user.id' => 'user_group.id_user']);
}
That would give you the Group(s) a User belongs to. But I think you are aiming to get the Users that belong to a given group, so similarly I would create a getUsers relation in your Group model:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('group_user', ['group_id' => 'id']);
}
Then:
$group = Group::findOne($id_group);
$users = $group->getUsers()->all();

Zend Framework 2 can't get fields from joined tables

I can't get fields from the joined table. Here is my situation, I have two tables called "query" and "region" handeled by two controllers QueryCOntroller and RegionController. From the QueryController I tried to join the "query" to "region". to get the name of "query"'s "region"'s name in a view file but I can't get the desired field
public function fetchMine($myid)
{
$sql = new Sql( $this->tableGateway->adapter ) ;
$where = new Where() ;
$where->equalTo('agent_id', $myid) ;
$select = $sql->select() ;
$select -> from ( $this->tableGateway->getTable() )
-> join ( 'region' , 'query.agent_id = region.id')
->columns(array('*'))
-> where( $where ) ;
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
in my Module.php, getServiceConfig()
'Management\Model\QueryTable' => function($sm) {
$tableGateway = $sm->get('QueryTableGateway');
$table = new QueryTable($tableGateway);
return $table;
},
'QueryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Query());
return new TableGateway('query', $dbAdapter, null, $resultSetPrototype);
},
try:
public function fetchMine($myid)
{
$select = new Select ();
$select->from ( $this->tableGateway->getTable() );
$select->join ( 'region' , 'query.agent_id = region.id' , Select::SQL_STAR , Select::JOIN_LEFT )
$select->where( array( 'agent_id'=>$myid ) );
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
then you must extends Query from Region for getting all attributes of query and region,
Query.php:
use Management\Model\Region;
class Query extends Region
{
//...
}
The Query class must have attribute has the same name of region name in region table
if you want to use another name just use sql alias
if you want to add more attributes from region table you must add them all in Query class

Insert a duplicate record based on value of another column

I have a db table named Student, with columns as id, name, age.
id is the Primary Key, name is not null, and age can be null
I want to implement the following in php, Zend:
Only add a duplicate student name in db if the age value is different.
Inside the function/action addStudentAction, I am calling the Student model's function -findStudent to implement the requirement:
public function findStudent($name)
{
$result = null;
$select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
->setIntegrityCheck(false)
->where('student.name = ?', $name);
//error_log($select->assemble());
$result = $this->getAdapter()->fetchRow($select);
return $result;
}
public function addStudentAction() {
$data = $_POST;
$studentModel = new Application_Model_Student;
$result = $studentModel->findStudent($data['name']);
if(!empty($result)) {
error_log("found student name in db, going to get age");
//Check for age
if( (!empty($result['age'] )) {
if( $result['age'] != $data['age']) {
error_log("going to add student as new record");
return $this->insert($data);
}
else {
error_log("not adding new student record ");
}
}
}
}
Now, there could be multiple records of Students with same name but different age values. Therefore, when adding a new student, I need to compare the ages of all records(if name matches) with the incoming value of age.
What could be best way to implement this requirement? Any help is greatly appreciated.
Thanks
The easiest way would be to create a compound UNIQUE index on the name, then age field. UNIQUE allows multiple NULL values, so that won't be an issue. Depending on your database size and usage, this might not be the most preferred option, in which case a simple SELECT of the student information before an INSERT to check if he/ she is already in there would be the best solution.
Let me know if I need to elaborate on this. I'd be happy to give you some examples.
How about you do a new SELECT with name and age:
public function findStudentWithAge($name, $age =null)
{
$result = null;
$select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
->setIntegrityCheck(false)
->where('student.name = ?', $name);
if($age) $select->where('student.age = ?', $age);
//error_log($select->assemble());
$result = $this->getAdapter()->fetchRow($select);
return $result;
}
Now in the addStudentAction:
public function addStudentAction() {
$data = $_POST;
$studentModel = new Application_Model_Student;
$result = $studentModel->findStudent($data['name'], $data['age']);
if(!empty($result)) {
error_log("found student with this age, cannot add the record");
} else {
$this->insert($data);
}
}