Laravel, Eloquent n:m relationship - laravel

I try do define a n:m relationship in Laravel using Eloquent. I have the following tables given:
users:
ID
foo
things
ID
users_things
thing_id
foo
In my User Model I have defined the following relation
public function things() {
return $this->hasMany('App\Thing', 'user_things', 'foo', 'thing_id');
}
In the Things Model is the counterpart
public function users() {
return $this->hasMany('App\User', 'user_things', 'thing_id', 'foo');
}
When I call in the Controller
$user = User::find(1) //works
//$thing = Thing::find(1) works
$things = $user->things();
return $things
I get the following message:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could
not be converted to string.
My problem is that, I cannot use the User ID as foreign key in the combination table. It has to be the foo column.

You may try this (Use belongsToMany for many-to-many relationship):
// User.php
protected $primaryKey = 'foo';
public $incrementing = false;
public function things() {
return $this->belongsToMany('App\Thing', 'user_things', 'foo', 'thing_id');
}
// Thing.php
public function users() {
return $this->belongsToMany('App\User', 'user_things', 'thing_id', 'foo');
}
Finally, use $user->things instead of $user->things().

Related

Eloquent 'with()' returns null

I have a simple relationship between two models: User and Prescription. A user has many prescriptions. In the PrescriptionsController, when I try to get the user that the prescriptions belongs to, it returns null when using with().
PrescriptionsController
public function index()
{
$user_id = Auth::id();
$prescriptions = Prescription::with('user')->where('prescription_for', $user_id)->get();
return response()->json($prescriptions);
}
The result from that Eloquent query:
[{"id":1,"prescription_for":1,"prescription_by":1,"prescription_content":"Paracetamol 120mg - O cutie. Mod administrare: 1 Dimineata | 0 Pranz | 0 Seara","created_at":"2020-10-13T17:33:35.000000Z","updated_at":null,"user":null}]
You can see that the last parameter is null.
In my User model, I have set up the relationship using:
public function prescriptions()
{
return $this->hasMany(Prescription::class);
}
And the Prescription model:
protected $table = 'prescriptions';
public $primaryKey = 'id';
public $timestamps = true;
public function user()
{
return $this->belongsTo(User::class);
}
I am using VueJs so I cannot just do $prescription->user->name as you can in Blade files, that's why I need to eager load the data.
The way I set up the Prescriptions table:
$table->id();
$table->unsignedBigInteger('prescription_for');
$table->foreign('prescription_for')->references('id')->on('users');
$table->unsignedBigInteger('prescription_by');
$table->foreign('prescription_by')->references('id')->on('users');
$table->string('prescription_content');
$table->timestamps();
Any ideas to why this happens? Thanks!
On your prescriptions table, your primary key is prescription_for. If the parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo() method specifying the parent table's custom key :
public function user()
{
return $this->belongsTo(User::class, 'id', 'prescription_for');
}

Laravel hasMany relationship issue

I have a problem about table relationship in models. when I try to add hasMany relation there is an error popping up.
Call to undefined relationship [Plan100] on model [App\AllPlan].
This is the main table model places
protected $table = "places";
public $with = ["AllPlan"];
public function allplans()
{
return $this->hasMany("App\AllPlan");
}
And AllPlan table model
protected $table = "all_plans";
public function place()
{
return $this->belongsTo("App\Place");
}
No problem 'till here. I can see the AllPlan data inside the Places table on json response... But, the problem is popping up when I try to add hasMany relation into AllPlan table like below.
Now AllPlan table model looks like this.
protected $table = "all_plans";
public $with = [
"Plan100",
"Plan90",
];
public function place()
{
return $this->belongsTo("App\Place");
}
public function plan()
{
return $this->hasMany(
"App\Plan100",
"App\Plan90"
);
}
And the Plan100 table model look like this:
public function plan()
{
return $this->belongsTo("App\AllPlan");
}
But it's giving me an error. But I am not very sure where do I do wrong. Thank you.
Seems to me that you are trying to create two new relations, but this can't be done inside one function. Create two functions and refactor your code like this:
public function plan100()
{
return $this->hasMany(App\Plan100", 'foreign_key');
}
public function plan90()
{
return $this->hasMany(App\Plan90", 'foreign_key');
}

Laravel relations pivot table name trouble

in my app I have 2 conversations types: normal private conversations between users and conversations for people which are interested of user product.
In my User model I declared relations like:
public function conversations()
{
return $this->belongsToMany('App\Conversation', 'conversation_user');
}
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
Where 'conversation_user' and 'conversation_product_user' are pivot tables between 'users'-'conversations' and 'users'-'conversations_product' tables.
My conversation_user pivot table has conversation_id and user_id table properties, but conversation_product_user pivot table has additional property product_id.
In my Conversation Model I have:
public function users()
{
return $this->belongsToMany('App\User');
}
public function messages()
{
return $this->hasMany('App\Message');
}
In ConversationProduct Model I wrote:
protected $table = 'conversations_product';
public function users()
{
return $this->belongsToMany('App\User', 'conversation_product_user');
}
public function messages()
{
return $this->hasMany('App\MessageProduct');
}
In my ConversationProductController I have method to find user conversations:
public function showUserConversationsProduct(Request $request){
$user_id = $request->user_id;
//var_dump($user_id);
$userData = User::where('id', $user_id)->with('conversationsProduct')->first();
}
And there is my problem: In controller ->with('conversationsProduct') don't take relation for conversation_product_user, but for conversation_user pivot table. I can't handle it why its happen if I add second parameter as 'conversation_product_user' in my relation:
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
I need protected $table = 'conversations_product'; to point my ConversationsProductController#store where to save conversation, but I think that can be problem with recognise proper relation.
I really appreciate any help. I attach photo of my db relations.

Laravel Nested Relationship Where 5.5 Return All Records

I'm having some trouble when trying to fetch records from database. Here's the table schema:
users
--------------
id
username
password
email
divisions
--------------
id
name
employee
--------------
name
birth_date
status
class
division_id
user_id
projects
--------------
id
title
body
user_id
So, for the relationship explanations:
relationship
Okay, i'm trying to fetch project based on division_id on table employee with the following code:
# query code
$division_id = 10;
$items = Project::with(['user.employee.division' => function($query) use ($division_id) {
$query->where('id', $division_id);
}])->get();
I've added the required belongsTo, hasMany or hasOne to the models.
# User.php
class User extends Authenticatable
{
public function employee()
{
return $this->hasOne('App\Employee', 'user_id');
}
public function projects()
{
return $this->hasMany('App\Project', 'user_id');
}
}
# Division.php
class Division extends Model
{
public function employee()
{
return $this->hasMany('App\Employee', 'division_id');
}
}
# Employee
class Employee extends Model
{
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
public function division()
{
return $this->belongsTo('App\Division', 'division_id');
}
}
# Project.php
class Project extends Model
{
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
So, what's the problem?
Here's the thing, when i run the query code i'm getting all the records and the division object on employe relationship returning null.
If anyone thinks my code is wrong, please enlighten me.
Thanks.
So after some digging, i found an answer. The query code should change to whereHas:
# query code
$division_id = 10;
$items = App\Project::whereHas('user.employee.division',
function($query) use ($division_id) {
$query->where('divisions.id', $division_id);
})
->with(['user.employee.division']) // N+1 problem
->get();
reference: Laravel 5.3 Constraining Eager Loads not working

Laravel Eloquent - Get all records of child relation model

My data model is this:
Users > Offices > Organization
This is my model
class Organization extends Model {
protected $table = 'organizations';
public function offices()
{
return $this->hasMany('App\Models\Office');
}
public function users()
{
return $this->offices()->users();
}
....
So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like
$this->offices()->users();
(Avoiding user a manual collection or map to do that)
Thanks!
So, you have organization ID. You can load all users by using whereHas():
$users = User::whereHas('office', function ($q) use ($organizationId) {
$q->where('organization_id', $organizationId);
})
->get();
Make sure office() relationship is defined correctly in User model:
public function office()
{
return $this->belongsTo('App\Office');
}
Alternatively, you could define hasManyThrough() relationship:
public function users()
{
return $this->hasManyThrough('App\Office', 'App\User');
}
And use it:
$organization->users()

Resources