i have pivot table like this
this is my Users model
public function getHousing()
{
return $this->belongsToMany(Housing::class, 'user_housing', 'user_id', 'housing_id')->withPivot('primary');
}
this is my Housing model
public function getUser()
{
return $this->belongsToMany(Users::class, 'user_housing', 'housing_id', 'user_id')->withPivot('primary');
}
i want to save primary with 1, this is my controller
$getData = $this->crud->show($id);
if (!$getData) {
return redirect()->route('admin.' . $this->route . '.index');
}
$data = $this->validate($this->request, [
'housing_group_id' => 'required',
'housing_id' => 'required',
'primary' => 'required',
]);
$getData->housing_id = $getData->getHousing()->pluck('id')->toArray();
$getData->getHousing()->sync($this->request->get('housing_id'), ['primary' => 1]);
$id = $getData->id;
i already add array fill primary 1, but i have error like this
SQLSTATE[HY000]: General error: 1364 Field 'primary' doesn't have a default value
how to save additional field in pivot table laravel ?
thanks
in sync with additional column in pivot table, you should pass an associative array for each id with column name as key and field value as value
$elements_array[$this->request->get('housing_id')]=['primary' => 1]
$getData->getHousing()->sync(elements_array);
if you have more than an 'id' to sync ... you must repeat the first step for each id.
check this:
https://stackoverflow.com/a/27230803/10573560
Related
I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),
i have pivot table call user_privilege,
user_id,
privilege_id
house_group_id,
i use method sync for store data into pivot tabl, this is my method
$data = $this->getCollectedData($getListCollectData, $viewType, $data);
$getData = $this->crud->store($data);
$getData->getPrivilege()->sync([
'user_id' => $getData->id,
'house_group_id' => $this->request->get('house_group_id'),
'privilege_id' => 3,
]);
this is my getPrivilege() method in Users Model
public function getPrivilege()
{
return $this->belongsToMany(Privilege::class, 'user_privilege', 'user_id', 'privilege_id', 'house_group_id');
}
but when i click submit, return error like this
SQLSTATE[HY000]: General error: 1364 Field 'house_group_id' doesn't have a default value (SQL: insert into `user_privilege` (`privilege_id`, `user_id`) values (b3f08343-a8f6-4a45-b7bc-b396125634d3, ?))
when i dd($this->request->get('house_group_id')) return ID house_group_id like this
"2539d741-1526-4c42-b57a-da60e2e862d8"
this is UUID from house_group_id,
Whats wrong in My Code, how to save data with addtional pivot table ?
thanks
The solution to this is probably easy and I'm just missing it, but I can't seem to figure out how to limit "customers" based on the "user" that the customer belongs to.
This is a many to many relationship, so a customer can belong to more than one user and a user can have more than one customer.
Here is my relationship definition:
public $belongsToMany = [
'user_id' => [
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
]
];
And here is the scope function that doesn't work as I'd expect:
public function scopeUser($query) {
$user = Auth::getUser()->id;
return $query->where('user_id', $user)->get();
}
Finally, here is my error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from `tblcustomers` where `user_id` = 1)
Obviously, the error is because the "user_id" column doesn't exist in the 'tblcustomers' table, but rather in the pivot table. How can I use the "user_id" from the pivot table in my scope function? I need to only display Customers that belong to the currently logged in user.
Yes this can be possible
But First thing is you need to remove get() method from the scope, scope meant to return query object for chaining methods further.
Your relation and scope should look like this
// relation
public $belongsToMany = [
// PLEASE MAKE RELATION NAME CORRECT HERE
'users' => [ // not user_id, use `users`
'RainLab\User\Models\User',
'table' => 'tablename_users_customers',
// 'key' => 'customer_id', if needed
// 'otherKey' => 'user_id' if needed
]
];
// scope
use RainLab\User\Models\User;
public function scopeUser($query) {
return $query->whereHas('users', function($usersQuery) {
$user_id = Auth::getUser()->id;
return $usersQuery->where((new User)->getTable() . '.id', $user_id);
});
}
// usage
$result = Customer::user()->get();
dd($result);
// you will get only customers which has relation with current logged in user.
if any doubts please comment.
I try to update my table Item but I use unique validation in my controller, I have set the primary key = 'item_id' in my model but I keep get this error said unknown column id even though I have set the primary key as item_id in my model, when I try to use validation :
// 'barcode' => 'unique:item' //
This error doesn't appear and the program works but in the unique of barcode it is checking itself for the unique column and it fails but seeing its own field. that's why i change my validation become this :
// 'barcode' => 'unique:item,barcode,'.$item_id, //
when I try to update I get this error :
Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from item where barcode = A002 and id <> 12)
ItemController :
public function update(Request $request,$item_id)
{
$messages = [
'unique' => 'Sorry this barcode already exist....',
];
$this->validate($request,[
'barcode' => 'unique:item,barcode,'.$item_id,
],$messages);
$data = $request->except(['_token']);
Item::where('item_id',$item_id)->update($data);
return redirect('/item')->with('sukses','item successfully updated');
}
this is my model
Item.php :
class Item extends Model
{
protected $table = 'item';
protected $primaryKey = 'item_id';
protected $fillable = ['barcode','item_name','category_id','satuan_id','price'];
public function category_r(){
return $this->belongsTo('App\Category','category_id','category_id');
}
public function satuan_r(){
return $this->belongsTo('App\Satuan','satuan_id','satuan_id');
}
}
When you are using custom primary key you should also add its name to the validation:
$this->validate($request,[
'barcode' => 'unique:item,barcode,'.$item_id.',item_id'
],$messages);
https://laravel.com/docs/5.2/validation#rule-unique
I want to update my table where the input the same input fields names are array and has
add more function which generates the input fields like this:
I want to do update_batch in codeigniter
my model i created a function like this:
This is the code block:
function update_batch_all($tblname,$data=array(),$userid)
{
$this->db->trans_start();
$this->db->where('userid',$userid);
$this->db->update_batch($tblname,$data);
$this->db->trans_complete();
return TRUE;
}
it is not working.
can any one help me that how can i update tables data with update batch that has where condition?
You can read the docs for update_batch() here
Here's the short summary:
You pass in an associative array that has both, your where key, and the update value. As the third parameter to the update_batch() call, you specify which key in your assoc array should be used for the where clause.
For example:
$data = array(
array(
'user_id' => 1,
'name' => 'Foo'
), array(
'user_id' => 2,
'name' => 'Bar'
)
);
$this->db->update_batch($tbl, $data, 'user_id');
Breakdown of arguments passed:$tbl is the table name. $data is the associative array. 'user_id' tells CI that the user_id key in $data is the where clause.
Effect of the above query: Name for user with user_id = 1 gets set to Foo and name for user with user_id=2 gets set to Bar.
In your case, if you want to set the same user_id key in each array with your data array, you can do a quick for loop:
foreach ($data as &$d) {
$d['user_id'] = $user_id;
}
$this->db->update_batch($tbl, $data, 'user_id');
You can use,
$this->db->update_batch($tblname,$data,'user_id');
But all array within data must have a field 'user_id'
eg:
$data=array(
array('user_name'=>'test1','user_id'=>1),
array('user_name'=>'test2','user_id'=>2)
);
You can get more details about update_batch from here