Laravel belongsTo relationship returns null - laravel

I'm building a rudimentary CRM app using Laravel 6.0. Users can freely create accounts, but to get any functionality out of the app, they need to set up a SubscriptionAccount (or join an existing one), which will then allow them to create/manage customer Accounts, add Users, etc. (each is a one to many).
The User model's relationship to SubscriptionAccount model is giving me issues. For example:
$user = User::find(1);
$user->subscription()->create(['name' => 'Test Subscription']);
$user = $user->fresh();
dd($user->subscription); // returns null
I suspected it had to do with the belongsTo relationship in the User model, but the odd thing is that it actually creates and persists a new SubscriptionAccount while using that relationship (second line above), though if you access users relationship from the new SubscriptionAccount it also returns null.
Here are the models:
// User.php
class User
{
public function subscription()
{
return $this->belongsTo(SubscriptionAccount::class, 'subscription_account_id');
}
}
// SubscriptionAccount.php
class SubscriptionAccount extends Model
{
public function users()
{
return $this->hasMany(User::class, 'subscription_account_id');
}
}
The only thing out of the ordinary is shortening the name of the relationship to subscription from SubscriptionAccount, but that should have been taken care of by specifying the foreign key in both relationships. Here's the migrations:
Schema::create('subscription_accounts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('uuid')->unique();
$table->string('name');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('uuid')->unique();
$table->bigInteger('subscription_account_id')->unsigned()->index()->nullable();
$table->string('name');
...
$table->timestamps();
$table->foreign('subscription_account_id')
->references('id')
->on('subscription_accounts');
});
If I create the user from a SubscriptionAccount (i.e. $subscriptionAccount->users()->create([...]); it sets the correct subscription_account_id on the users table, but doesn't work vice versa.

This is a known issue (feature?) with the belongsTo relationship:
https://github.com/laravel/framework/issues/29978
To work around it you can associate the models manually:
$user = User::find(1);
$sub = Subscription::create(['name' => 'Test Subscription']);
$user->subscription()->associate($sub);
$user->save();

So instead of using belongsTo because a subscription account does not belongs to one user, it can belong to many, you might want to use the hasOne relationship instead:
public function subscription()
{
return $this->hasOne(SubscriptionAccount::class, 'id', 'subscription_account_id');
}
It will belongTo one User if you had a user_id within the subscription_accounts table.
Let me know if it makes sense and if it works :)

Related

Laravel Many To Many Relationship between Three Models

I want to create a relationship between the three models. My models are
Users
-- Database Structure
id
name
---
Books
-- Database Structure
id
name
BookShelf
-- Database Structure
id
name
1: User has many books and book belongs to many users
2: User's book belongs to one BookShelf and user's BookShelf has many books.
How can I define the relationship between these three models? I am building an application something like Goodreads.
You have a many to many relationship between your User and Book, as well as a many to many between your Book and BookShelf.
This type of relationship is managed by a pivot table behind the scenes, so you will require two pivot tables.
Pivot between User and Book
Create your migration
php artisan make:migtration create_book_user_table
Define your relationship
public function up()
{
Schema::create('book_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('user_id')->constrained();
$table->foreignId('book_id')->constrained();
});
}
Pivot between Book and BookShelf
Create your migration
php artisan make:migtration create_book_book_shelf_table
Define your relationship
public function up()
{
Schema::create('book_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('book_id')->constrained();
$table->foreignId('book_shelf_id')->constrained();
});
}
With the pivot tables create you can add the relationships to your models.
User
public function books()
{
return $this->belongsToMany(Book::class);
}
Book
public function users()
{
return $this->belongsToMany(User::class);
}
public function bookshelves()
{
return $this->belongsToMany(BookShelf::class);
}
BookShelf
public function books()
{
return $this->belongsToMany(Book::class);
}
Now you have your relationships, you can access them on your User. As an example:
Route::get('/', function () {
$user = User::where('id', 1)->with(['books', 'books.bookshelves'])->first();
return view('user', compact('user'));
});
user.blade.php
<h3>{{ $user->name }}</h3>
<h4>Books</h4>
#foreach ($user->books as $book)
<h5>{{ $book->name }}</h5>
<p>Can be found on #choice('shelf|shelves', $book->bookShelves()->count())</p>
#foreach ($book->bookShelves as $shelf)
<li>{{ $shelf->name }}</li>
#endforeach
#endforeach
The above would iterate over each Book for the $user and then iterate over each of the BookShelves that Book is related to.
Update
If a Book can only belong to one Bookshelf, you need to alter your books table.
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->foreignId('bookshelf_id')->constrained('book_shelves');
});
}
You will also need to alter the relationship on your Book model:
public function bookshelf()
{
return $this->belongsTo(BookShelf::class);
}
This way a Book can now only belong to one Bookshelf.
If a User can only have one Bookshelf, again you need to alter your book_shelves table:
public function up()
{
Schema::create('book_shelves', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->foreignId('user_id')->constrained();
});
}
Then add the relationship to your User.
public function bookshelf()
{
return $this->hasOne(BookShelf::class);
}
You should then be able to access the Bookshelf for a User directly.
$user->bookshelf->books
1: User has many books and book belongs to many users
User has a Many To Many relationship with Book
// User model
public function books()
{
return $this->belongsToMany(Book::class, 'book_user');
}
Book has a Many To Many relationship with User
// Book model
public function users()
{
return $this->belongsToMany(User::class, 'book_user');
}
2: User's book belongs to many BookShelf and BookShelf has many books.
Book has a Many To Many relationship with Bookshelf
// Book model
public function bookshelves()
{
return $this->belongsToMany(Bookshelf::class, 'book_bookshelf');
}
Bookshelf has a Many To Many relationship with Book
// Bookshelf model
public function books()
{
return $this->belongsToMany(Book::class, 'book_bookshelf');
}
You'd need two pivot tables.
book_user
column
migration
id
$table->id()
book_id
$table->foreignId('book_id')->constrained('books')
user_id
$table->foreignId('user_id')->constrained('users')
book_bookshelf
column
migration
id
$table->id()
book_id
$table->foreignId('book_id')->constrained('books')
bookshelf_id
$table->foreignId('bookshelf_id')->constrained('bookshelves')
Let's start from first task:
1: User has many books and book belongs to many users
In this case it is many-to-many relationships. To implement this setup you need users table like this:
Users: id, name, someotherdata
then you need books table:
books: id, name, bookdata
and then you need the third table to connect them many to many:
users_books: id, book_id, user_id
In this case when you need all books which belongs to one user you can select from users_books where user_id=someuserid and join it with books table and you will receive all books which belongs to some user.
Visa versa you can receive all users who posses some particular book.
2: User's book belongs to one BookShelf and user's BookShelf has many books.
For this you would have to create table bookshelfs: id, name
And add foreign key to books table as bookshelf_id
Then your books table will look like this:
books: id, name, bookdata, bookshelf_id.
So when you need to get all books from shelf just filter select from books where bookshelf_id = someid

Eloquent Relationships Not Working as Expected

I am trying to understand what I am missing here.
Apps migration
Schema::create('apps', function (Blueprint $table) {
$table->increments('id');
$table->integer('show_id')->unsigned()->index();
$table->string('name');
$table->integer('provider_id')->unsigned()->index();
$table->timestamps();
});
Show migration
Schema::create('shows', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
So I create an apps model that has the following function
public function Show() {
return $this->hasOne(Show::class);
}
But in php artisan tinker when I do $app->Show; I get the following error:
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1 no such column: shows.app_id (SQL: select * from "shows" where "shows"."app_id" = 1 and "shows"."app_id" is not null limit 1)'
Am I mis-understanding the relationships?
Your relation should be as:
Apps model:
public function show() {
return $this->hasOne(Show::class, 'id', 'show_id');
}
Or it can be:
public function show() {
return $this->belongsTo(Show::class);
}
Docs
You do not have an app_id in your shows migration.
edit: Taking from the Laravel Docs and changing it to fit your situation
Eloquent determines the foreign key of the relationship based on the model name. In this case, the show model is automatically assumed to have a app_id foreign key.
A one-to-one relationship consists of a hasOne and a belongsTo. The table that contains the foreign key field must be on the belongsTo side of the relationship.
Since your apps table contains the show_id field, it is stated that apps belong to shows, and shows has one (or many) apps.
Given this, you need to change your Show relationship on your Apps model to use the belongsTo relationship.
public function Show() {
return $this->belongsTo(Show::class, 'show_id');
}
Unless you rename your relationship method so that it is lowercase (function show()), the second parameter is required. If you renamed the relationship, Laravel could build the proper key name and you could leave off the second parameter:
public function show() {
// For belongsTo, second parameter defaults to {function_name}_id.
return $this->belongsTo(Show::class);
}
In your apps model :
public function Show() {
return $this->belongsTo('yourmodelnamespace\Show','id','show_id');
}
And you need create Show model too ..
Hope it will works~~
You can use relation like this
public function Show() {
return $this->hasOne(Show::class, 'id','id');
}

Laravel Eloquent Relationship Many to Many Naming Convention

I am creating a purchased table in my application. So I have 2 tables : User and Product. Its a many to many relationship.
I know we have to create a new table for this. The naming convention for table is plural as users and products.
How would we call this purchase table? user_product or users_products?
Also I think I would need a model for this correct? If I do need a model should the naming convention for this model be User_Product?
From the documentation:
As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method
In your case, Laravel assumes that your joining table would be named product_user. No extra model is needed:
User.php
class User extends Model
{
//...
public function products()
{
return $this->belongsToMany(Product::class);
}
//...
}
Product.php
class Product extends Model
{
//...
public function users()
{
return $this->belongsToMany(User::class);
}
//...
}
And your schemas would look like so:
users table migration
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
//...
});
products table migration
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
//...
});
product_user table migration
Schema::create('product_user', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('user_id');
//...
});
About the naming Convention, thats just something that will make your code more readable i think, so you can name it as you like(in case you are new and learning , my opinion is that its better to avoid being stuck in conventions at first , im still learning my self)
anyway a pivot model is not required, unless you simply need some custom behaviour
I think this would help you
class User extends Model
{
/**
* The products that belong to the shop.
*/
public function products()
{
return $this->belongsToMany('App\Products');
}
}
you can do this : $user->products or to query $product->users, or both.
Now, with such declaration of relationships Laravel “assumes” that pivot table name obeys the rules and is user_product. But, if it’s actually different (for example, it’s plural), you can provide it as a second parameter:
return $this->belongsToMany('App\Products', 'products_users');
If you want to know how to manage these you can find more in here

Many to Many relationship works one way

I have a User and a Quiz models. I have many-to-many relationship defined between them in the following way:
User model
public function subscriptions()
{
return $this->belongsToMany(Quiz::class, 'subs_users', 'user_id', 'quiz_id')->withTimestamps()->withPivot('accepted');
}
Quiz model
public function subscribers()
{
return $this->belongsToMany(User::class);
}
Pivot table
Schema::create('subs_users', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('quiz_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('quiz_id')->references('id')->on('quizzes')->onDelete('cascade');
$table->primary(['user_id', 'quiz_id']);
$table->boolean('accepted')->index();
$table->timestamps();
});
When I call $quiz->subscribers, it returns a collection of users as expected. However, $user->subscriptions always returns an empty array. Why is that?
Edit
It seems, that replacing this line in Quiz
return $this->belongsToMany(User::class);
with
return $this->belongsToMany(User::class, 'subs_users', 'quiz_id', 'user_id')->withTimestamps()->withPivot('accepted');
Solves the issue, but I still can't understand why the first variant does not work.
Look at this:
public function subscriptions()
{
return $this->belongsToMany(Quiz::class, 'subs_users', 'user_id', 'quiz_id')->withTimestamps()->withPivot('accepted');
}
You mixed the foreign key with other key: user_id and quiz_id.
Remember when doing many to many relation that: first of foreign key's declared in belongsToMany is a key related to the current model.
Replacing belongsToMany() relationship in Quiz model with following:
return $this->belongsToMany(User::class, 'subs_users');
Solves the issue. It seems, that when a non-standard name is used for the pivot table, both sides must explicitly state it. In other words, 'subs_user' pivot table name must be present in belongsToMany() relationship declarations in both models.

Stuck at defining relationship in laravel 4

i'm trying to understand laravel by creating a messaging application. User should be able to send message to each other. i have made a similar application using core php.
I'm done with login/authentication and migration and now stuck at defining relationship in models;
i have created 3 tables using migrations:
users
conversations
conversations_reply
This is the Schema of:
users table (For storing detail of users)
$table->increments('id');
$table->string('username', 50);
$table->string('password', 50);
$table->string('name', 50);
$table->string('email', 254);
$table->timestamps();
conversations table(For storing conversation between users)
$table->increments('id');
$table->integer('user_one'); //foreign key of one friend from users table
$table->integer('user_two'); //foreign key of second friend from users table
$table->string('ip');
$table->timestamps();
conversations_reply table(For storing Conversation text)
$table->increments('id');
$table->text('reply');
$table->integer('user_id');
$table->integer('conversation_id'); //foreign key of conversations table
$table->string('ip');
$table->timestamps();
Now, i'm trying to define relationships in models as:
User model wil have hasMany relationship with both Conversation and ConversationReply model.
Conversation will have belongsToMany relationship with User model and hasMany relationship with ConversationReply model.
ConversationReply model will have belongsToMany relationship with both User and Conversation model.
Now i'm stuck at defining relationship in the first model(User)and unable to proceed further because i need to define local and foreign key, but i'm unable to do so because conversations table will have 2 foreign keys(of 2 users) and i can define only one foreign key.
Edit: There should be only two members in a conversation and and two users should have only one conversation(like facebook). Their new messages should be added to their old conversations. In conversations table, ip is the ip address of the user who would start the conversation and in the conversations_reply table, ip is the respective ip of the user
There seems to be a little flaw in your abstraction. You have actually designed user1 and user2 as attributes of the Conversation entity, but they are not attributes. Also, what is the IP of a conversation?
Attributes of a Conversation may be topic, start time, end time, amount of messages and things like that.
And then a conversation has members. Not exactly two but many. So you could just create an entity / model ConversationMembers that connects User and Conversation:
conversation_members table:
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->string('ip');
$table->string('nickname');
and change the conversations table accordingly:
$table->increments('id');
$table->boolean('public);
// other attributes you're interested in
$table->timestamps();
Now you can define the relationships on your models:
Conversation:
public function members()
{
return $this->hasMany('ConversationMember');
}
public function messages()
{
return $this->hasMany('ConversationReply');
}
ConversationMember:
public function user()
{
return $this->belongsTo('User');
}
public function conversation()
{
return $this->belongsTo('Conversation');
}
User:
public function conversations()
{
return $this->hasManyThrough('Conversation', 'ConversationMember');
}
public function replies()
{
return $this->hasMany('ConversationReply');
}
I hope this helps.

Resources