I'm just trying to use BelongsTo relationship to retrieve the records,
Here is the scheme:
roles:
- id
- title
users:
- id
- Role_ID
I'm using SQL Server for Database so the Role_ID can pointed as role_id I think :D.
and here is the code for the belongs to relationship in User Model:
public function role()
{
return $this->belongsTo('App\Role');
}
I also have tried like this:
public function role()
{
return $this->belongsTo('App\Role', 'id', 'Role_ID');
}
But whatever the parameters are it doesn't work and when I get the Query log, it looks like as:
bindings: []
query: "select * from [roles] where 0 = 1"
time: 1.49
Here is how I try to access the relation in the Controller:
User::with(['role'])->get($someColumns)
I'm just fighting with this problem for many times but don't know where the issue is.
Any help is appreciated.
Thanks everybody.
You have to include the foreign key in get() columns
User::with(['role'])->get(Role_ID, OthersColumns)
Try this relationship in your model.
public function role()
{
return $this->belongsTo('App\Role', 'Role_ID','id');
}
Thanks guys, #Dilip hint helped me to solve the problem.
Please see my updated question this line:
User::with(['role'])->get($someColumns)
Actually the problem was with $someColumns, because when I was mentioning the name of some columns in get, it was causing the issue but when I replaced it with the following:
User::with(['role'])->get()
It worked,
So the simple solution is to not mention the columns name when getting with relationship belongsTo
Related
rI am new to laravel 7 and I still have a few small difficulties.
I have two tables: users and services. These two tables have a relation to retrieve a user's service.
$users= User::with('poseur')->get();
It returns all users even those who do not meet the conditions of my relationship.
I use scope in service model:
public function scopePoseurs(){
return $query->whereRaw('slug','pos')
}
And i use belongsTo relation in user model :
public function poseur(){
return $this->belongsTo('App\Service')->poseurs();
}
Exemple: we hase 2 users:
first: Daniel have service slug = 'pos',
second: Patrick have service slug ='dev'
When i use $users=User::with('poseur')->get();, i see Daniel and Patrick.
While there should be only Daniel.
Can you help me understand ?
Thanks !
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models.
If you want to return all user, that has relation with poseur only, then use has() method :
$users= User::has('poseur')->get();
Ther is also a method called whereHas(), which allows you to specify additional filters for the related model to check :
$users = User::whereHas('poseur', function($q){
$q->where('created_at', '>=', '2020-01-01 00:00:00');
})->get();
The question might sound a little bit confusing but I don't know how to explain it better in one sentence.
This describes basically what the problem is:
I have a Users table which can contain 2 types of users. I know how I can separate by role. But here's the thing, users with role 1(editor_in_chief) have different attributes than users with role 2(reviewer).
My idea was to create a table named 'reviewer_attributes' and 'editor_in_chief_attributes' and create a one-to-one relation with this table to hold the attributes for the users table.
Maybe you have a better idea, that would be great as well. But for this scenario, I would like to know if it is possible to make a call to the database and to get these users' properties from the other table as properties of the User object.
When using a DB call using relations laravel will give me something like this:
user {
id: 1,
name: "Name",
reviewer_attributes: {
attribute_1: 'attribute_1',
attribute_2: 'attribute_2',
attribute_3: 'attribute_3',
}
}
But this is what I want to object to obtain look like:
user {
id: 1,
name: "Name",
attribute_1: 'attribute_1',
attribute_2: 'attribute_2',
attribute_3: 'attribute_3',
}
I want to achieve this by a single database call instead of setting the properties after the call.
I find this a very interesting topic, I hope you could help!
If I got your problem right, you may call somthing like this:
DB::table('users')
->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
->find($id);
you may add select to get specific attributes of each table:
DB::table('users')
->join('reviewer_attributes', 'users.id', '=', 'reviewer_attributes.user_id')
->select('users.id', 'users.name', 'reviewer_attributes.*')
->find($id);
Update: You can also use collections to restructure your results returned by Eloquent:
$result = User::with('reviewerAttributes')->find($id);
$result = $result->get('reviewer_attributes')
->merge($result->forget('reviewer_attributes')->all())
->all();
You need export model to Json?
If so, override toArray method
public function toArray()
{
$arr = parent::toArray();
$reviewer_attributes = $this->getReviewerAttributesSomeHow();
return array_merge($arr, $reviewer_attributes);
}
I have a doubt and sure you can help me.
If I have a table user with 'work_id' row, and this value is a releated foreing key with the 'id' into 'work' table.
And into 'work' table I have a 'work_competence_id', and is a foreing key to 'work_competence' table.
And into 'work_competece' I have other row, 'competence_id', that is other foreing key, releated with the 'id' value into 'competence' table...
How can I get competence 'name' (for example) into my view.
I made some easy things, like show the work's name of each user, using
public function work()
{
return $this->hasOne('App\Work', 'id', 'work_id');
}
I put this code into User model.
And I use it into view with:
{{ $user->work->name }}
But, how is possible to do with so many relationships like I comment above??
Thank you!!
I am not sure, try:
public function competence(){
return this->work()->competence();
}
and in Work model create competence method
You can jump between more than just one relation:
// Work class
public function competence(){
return $this->hasOne('App\Competence', 'id', 'competence_id');
}
Then:
public function work(){
return $this->hasOne('App\Work', 'id', 'work_id');
}
Finally in your view:
{{ $user->work->competence->name }}
Using Cakephp 2.5.3 ... I have the following tables:
transactions (belongs to methods and deliveries)
id
delivery_id
method_id
methods (has many transactions)
id
name
deliveries (has many transactions)
id
date
In my delivery view I would like to see the method name for each delivery.
foreach ($deliveries as $delivery) {
echo $method['name'];
}
( a similar unanswered question is
here:)
I am (obv.) very new to Cakephp, What approach should I take to go about this? Thanks!
=========UPDATE==============
I ended up adding methods to the deliveries controller
$this->set('methods', $this->Method->find('all', array('recursive' => -1)));
And looped through the methods in my (read only) view :
//filtered method array for
$method['id'] == $delivery['Transaction']['0']['method_id'])
// got method name
$button_text = $method['name'];
It works fine but can anyone tell me if this may cause problems for me down the line?
use has many assotiations in Transaction model as -
public $hasMny = array('Method', 'Delivery');
then fetch them -
$this->set(
'methods',
$this->Method->find('all', array('contain' => array('Method', 'Delivery')))
);
you will get all the related result together.
I have posted a question and got help but I still dont make it.
Im trying to update a row in cakePHP 2.3.1.I have class Test extend AppModel with $validates array, and the Controller( simplified ) :
public function editstudent() {
if($this->request->data) {
$this->Test->stuId= $this->data['Test']['stuId'];
if ($this->Test->save($this->request->data)) {
$this->set('state',1);
}
}
My view after edit with suggestion from a user :D :
class Test extends AppModel {
var $name= 'Test';
var $primaryKey= 'stuId';
public $validate= array(.......);
}
I've set $primaryKey in View,set $this->Test->$primaryKey in controller but still got the error :
Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' SQL Query: INSERT INTO cakePhp.tests (stuName, stuDoB, stuAdd) VALUES ('Đào Đức Anh', '2013-03-25', 'Kim Liên')
Can anyone help me out,I really need help,I'm stuck at this for 2 day and cant figure it out :(
I think you have to change the following line
$this->Test->stuId = $this->data['Test']['stuId'];
to
$this->Test->id = $this->data['Test']['stuId'];
because it is the id property that contains the primary key value.
Quick attempt:
Try changing $this->data to $this->request->data in your controller code.
More things:
Bottom line, your primary key isn't getting set.
Try using (per the CakePHP book) this syntax:
public $primaryKey = 'stuId'; //notice "public" instead of "var"
check to find out why 'studId' isn't in the data being saved.
debug($this->request->data);
My assumption is, it's not in the request data - if it were, you'd be fine.
add the studId into the form that's being submitted or
get theID into the request data any other way you see fit
Side note:
you keep saying "view", but you really mean "model".
Add Your primary key in AppModel.php
public $primaryKey='username';