Laravel hasone не работает

Содержание
  1. Запутался с hasOne Eloquent Отношения Laravel
  2. 3 ответа
  3. 1-я ошибка: неправильное определение отношений
  4. 2-я ошибка: вы вызываете метод отношений, а не сами отношения
  5. Используйте Eager Загрузка
  6. Laravel hasone не работает
  7. User Model \n
  8. Profile Model \n
  9. User Model \r\n\r\n«`php\r\nuse MyNamespace\Models\Profile; \/\/ not necessary as they’re in the same namespace\r\n\r\npublic function profile() <\r\n return $this->hasOne(Profile::class);\r\n>\r\n«`\r\n\r\n
  10. Profile Model \r\n\r\n«`php\r\nuse MyNamespace\Models\User; \/\/ not necessary as they’re in the same namespace\r\n\r\npublic function user() <\r\n return $this->belongsTo(User::class);\r\n>\r\n«`\r\n\r\nTo save a new profile, you can do something like:\r\n\r\n«`php\r\n$user = auth()->user();\r\n\r\n$user->create([\r\n ‘firstname’ => $request->get(‘firstname’),\r\n ‘lastname’ => $request->get(‘lastname’),\r\n]);\r\n«`\r\n\r\nYou can then access a User’s Profile like so:\r\n\r\n«`php\r\n$user = auth()->user();\r\n\r\n$profile = $user->profile;\r\n«`\r\n\r\nAnd the inverse:\r\n\r\n«`php\r\n$profile = Profile::find(1); \/\/ get the first Profile\r\n\r\n$user = $profile->user;\r\n«`»,»replies»:[],»user»:<"id":3417,"username":"mstnorris","avatar":"\/\/unavatar.now.sh\/github\/mstnorris","experience":<"award_count":"332","level":50,"points":"515,885","pointsUntilNextLevel":"0">,»achievements»:[],»reported»:null,»profile»:<"github":"mstnorris","twitter":"mstnorris","full_name":null,"website":"https:\/\/michaelnorris.co.uk","bio":null>,»dateSegments»:<"created_diff":"7 years ago">>,»likes»:[],»created_at»:»2015-10-28T11:40:00.000000Z»,»links»:<"delete":"\/discuss\/replies\/110114","like":"\/discuss\/replies\/110114\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110116,"conversation_id":22665,"body":"

Запутался с hasOne Eloquent Отношения Laravel

У меня есть новое приложение Laravel 5.8. Я начал играть с Eloquent ORM и его отношениями.

Сразу возникла проблема, с которой я столкнулся.

У меня есть следующие таблицы. (это просто пример, по причинам тестирования, а не для реального применения)

То, что я хотел, это получить IP, принадлежащий фактическому логину.

Поэтому я добавил hasOne отношение к Login table , у которого есть внешний ключ для Data table :

Затем я добавил отношение hasOne к Data table , у которого есть внешний ключ для IP table :

Как только я закончил, я хотел получить IP-адрес для первой записи таблицы Login:

Но я получаю эту ошибку:

Что мне здесь не хватает и как я могу правильно получить IP этого логина? Мне нужен belongsTo где-нибудь?

3 ответа

1-я ошибка: неправильное определение отношений

Отношения Laravel двунаправлены. В one-to-one отношениях вы можете определить прямую связь ( HasOne ) и обратную связь ( BelongsTo )

Прямые отношения должны быть:

И обратные отношения должны быть:

См. Eloquent: отношения — индивидуальные документы для подробности о том, как это определить.

Обратите внимание , что вам не нужно определять оба направления для отношений, если вам это не нужно. В вашем случае, я думаю, вам просто нужно определить направление belongsTo .

2-я ошибка: вы вызываете метод отношений, а не сами отношения

Когда вы делаете:

Вы вызываете метод data , который определяет ваши отношения, а не связанную модель. Это полезно в некоторых случаях, но не в вашем случае.

Правильнее назвать магическое свойство отношения вместо этого:

Обратите внимание, что мы не используем () и нам здесь не нужен get() . Laravel позаботится о том, чтобы загрузить его для нас.

Используйте Eager Загрузка

У Laravel Eloquent есть Стремительная загрузка для отношений, которые в некоторых случаях очень полезны потому что это предварительно загружает ваши отношения, и уменьшает количество запросов, которые вы делаете.

В описанной вами ситуации (загрузка одной модели Login ) это не приводит к повышению производительности, но также не замедляет работу.

Это полезно, когда вы загружаете много моделей, поэтому уменьшает количество запросов к базе данных с N+1 до 2 .

Представьте, что вы загружаете 100 Login моделей, не стремясь загрузить, вы сделаете 1 запрос, чтобы получить свои Login модели, 100 запросов, чтобы получить ваши Data модели, и более 100 запросов, чтобы получить ваши Ip модели.

При активной загрузке он будет выполнять только 3 запроса, что приведет к значительному увеличению производительности.

С вашей структурой базы данных:

Данные для входа belongsTo

Data hasOne Войти

Data belongsTo IP

IP hasOne данные

После исправления ваших методов вы можете использовать ваши отношения, как это

Вы можете попробовать вот так:

А внутри data у вас будет ip как $login->data->ip .

Источник

Laravel hasone не работает

I’m struggling on making a hasOne relationship working. This is the context : \n

I have a users table built like this : \n

Schema::create(‘users’, function (Blueprint $table) <\n\n $table->increments(‘id’);\n $table->integer(‘profile_id’)->unsigned();\n \n $table->string(’email’, 100)->unique();\n $table->string(‘password’, 255);\n $table->rememberToken();\n\n $table->timestamps();\n>);\n \n

and a «profiles» table built like this: \n

Schema::create(‘profiles’, function (Blueprint $table) <\n\n $table->increments(‘id’);\n $table->integer(‘user_id’)->unsigned();\n\n $table->string(‘firstname’, 50);\n $table->string(‘lastname’, 50);\n\n $table->timestamps();\n>);\n \n

My User model has a profile() method defined like this: \n

public function profile()\n<\n return $this->hasOne(‘MyNamespace\\Models\\Profile’);\n>\n \n

And, to finish, my Profile model has the following method: \n

public function user()\n<\n return $this->belongsTo(‘MyNamespace\\Models\\User’, ‘user_id’);\n>\n \n

Problem is, when I save a new record using the following code: \n

$user = auth()->user();\n\n$profile = new Profile([\n ‘firstname’ => $request->get(‘firstname’),\n ‘lastname’ => $request->get(‘lastname’),\n]);\n\n$profile->user()->associate($user);\n$profile->save();\n\n$user = $user->profile()->save($profile);\n \n

the profile_id field in my «users» table remains empty. \n

Can some tell me what do I do wrong ? I’m pretty sure to have followed carefully the Laravel documentation \n

You don’t need $table->integer(‘profile_id’)->unsigned(); on the users table. \n

User Model \n

use MyNamespace\\Models\\Profile; \/\/ not necessary as they’re in the same namespace\n\npublic function profile() <\n return $this->hasOne(Profile::class);\n>\n \n

Profile Model \n

use MyNamespace\\Models\\User; \/\/ not necessary as they’re in the same namespace\n\npublic function user() <\n return $this->belongsTo(User::class);\n>\n \n

To save a new profile, you can do something like: \n

$user = auth()->user();\n\n$user->create([\n ‘firstname’ => $request->get(‘firstname’),\n ‘lastname’ => $request->get(‘lastname’),\n]);\n \n

You can then access a User’s Profile like so: \n

$user = auth()->user();\n\n$profile = $user->profile;\n \n

And the inverse: \n

$profile = Profile::find(1); \/\/ get the first Profile\n\n$user = $profile->user;\n \n»,»bodyInMarkdown»:»You don’t need `$table->integer(‘profile_id’)->unsigned();` on the `users` table.\r\n\r\n

User Model \r\n\r\n«`php\r\nuse MyNamespace\\Models\\Profile; \/\/ not necessary as they’re in the same namespace\r\n\r\npublic function profile() <\r\n return $this->hasOne(Profile::class);\r\n>\r\n«`\r\n\r\n

Profile Model \r\n\r\n«`php\r\nuse MyNamespace\\Models\\User; \/\/ not necessary as they’re in the same namespace\r\n\r\npublic function user() <\r\n return $this->belongsTo(User::class);\r\n>\r\n«`\r\n\r\nTo save a new profile, you can do something like:\r\n\r\n«`php\r\n$user = auth()->user();\r\n\r\n$user->create([\r\n ‘firstname’ => $request->get(‘firstname’),\r\n ‘lastname’ => $request->get(‘lastname’),\r\n]);\r\n«`\r\n\r\nYou can then access a User’s Profile like so:\r\n\r\n«`php\r\n$user = auth()->user();\r\n\r\n$profile = $user->profile;\r\n«`\r\n\r\nAnd the inverse:\r\n\r\n«`php\r\n$profile = Profile::find(1); \/\/ get the first Profile\r\n\r\n$user = $profile->user;\r\n«`»,»replies»:[],»user»:<"id":3417,"username":"mstnorris","avatar":"\/\/unavatar.now.sh\/github\/mstnorris","experience":<"award_count":"332","level":50,"points":"515,885","pointsUntilNextLevel":"0">,»achievements»:[],»reported»:null,»profile»:<"github":"mstnorris","twitter":"mstnorris","full_name":null,"website":"https:\/\/michaelnorris.co.uk","bio":null>,»dateSegments»:<"created_diff":"7 years ago">>,»likes»:[],»created_at»:»2015-10-28T11:40:00.000000Z»,»links»:<"delete":"\/discuss\/replies\/110114","like":"\/discuss\/replies\/110114\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110116,"conversation_id":22665,"body":"

You are putting the foreign key in both tables, it is useless. Remove the user_id column of the profile table, then User hasOne Profile and Profile belongsTo User. \n

The difference with hasOne and belongsTo is where the foreign key is. If the table contains a FK referencing the other table, then this is a belongsTo relationship, if the FK is in the other table referencing this one it is a hasOne relationship. belongsTo is the inverse of hasOne. \n»,»bodyInMarkdown»:»You are putting the foreign key in both tables, it is useless. Remove the user_id column of the profile table, then User hasOne Profile and Profile belongsTo User.\r\n\r\nThe difference with hasOne and belongsTo is where the foreign key is. If the table contains a FK referencing the other table, then this is a belongsTo relationship, if the FK is in the other table referencing this one it is a hasOne relationship. belongsTo is the inverse of hasOne.»,»replies»:[],»user»:<"id":6695,"username":"pmall","avatar":"\/\/unavatar.now.sh\/github\/pmall","experience":<"award_count":"608","level":50,"points":"555,695","pointsUntilNextLevel":"0">,»achievements»:[],»reported»:null,»profile»:<"github":"pmall","twitter":"pmallinj","full_name":null,"website":"","bio":null>,»dateSegments»:<"created_diff":"7 years ago">>,»likes»:[«flightsimmer668″],»created_at»:»2015-10-28T11:41:24.000000Z»,»links»:<"delete":"\/discuss\/replies\/110116","like":"\/discuss\/replies\/110116\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110118,"conversation_id":22665,"body":"

Ok guys I will try it your both ways then 🙂 \n

Ok just gave it a shot, and still it is not working 🙁 \n

I removed «profile_id» field in my users table, kept «user_id» field in profiles table and checked my User and profile models relationships which are just as above. \n

But when I run the following code I can’t retrieve my logged in user’s profile : \n

$user = auth()->user();\n\n$profile = new Profile([\n ‘firstname’ => $request->get(‘firstname’),\n ‘lastname’ => $request->get(‘lastname’),\n ‘organization’ => $request->get(‘organization’),\n ‘address1’ => $request->get(‘address1’),\n ‘address2’ => $request->get(‘address2’),\n]);\n\n$profile->user()->associate($user); \/\/ This correctly associate my user to the profile as user_id in profiles table is set correctly\n\n$user->profile()->save($profile);\n\ndd($user->profile); \/\/ But this is still giving me null :(\n \n»,»bodyInMarkdown»:»Ok just gave it a shot, and still it is not working :(\r\n\r\nI removed \»profile_id\» field in my users table, kept \»user_id\» field in profiles table and checked my User and profile models relationships which are just as above.\r\n\r\nBut when I run the following code I can’t retrieve my logged in user’s profile :\r\n\r\n«`php\r\n$user = auth()->user();\r\n\r\n$profile = new Profile([\r\n ‘firstname’ => $request->get(‘firstname’),\r\n ‘lastname’ => $request->get(‘lastname’),\r\n ‘organization’ => $request->get(‘organization’),\r\n ‘address1’ => $request->get(‘address1’),\r\n ‘address2’ => $request->get(‘address2’),\r\n]);\r\n\r\n$profile->user()->associate($user); \/\/ This correctly associate my user to the profile as user_id in profiles table is set correctly\r\n\r\n$user->profile()->save($profile);\r\n\r\ndd($user->profile); \/\/ But this is still giving me null :(\r\n«`»,»replies»:[],»user»:<"id":31142,"username":"arnaud-xp","avatar":"\/\/www.gravatar.com\/avatar\/092d276a8f7643dd576c433a276b5f01?s=100&d=https%3A%2F%2Fs3.amazonaws.com%2Flaracasts%2Fimages%2Fforum%2Favatars%2Fdefault-avatar-27.png","experience":<"award_count":"0","level":1,"points":"645","pointsUntilNextLevel":"4,355">,»achievements»:[],»reported»:null,»profile»:<"github":"","twitter":"","full_name":null,"website":"","bio":null>,»dateSegments»:<"created_diff":"5 years ago">>,»likes»:[],»created_at»:»2015-10-28T12:04:31.000000Z»,»links»:<"delete":"\/discuss\/replies\/110121","like":"\/discuss\/replies\/110121\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110122,"conversation_id":22665,"body":"

Are they set up like I showed you? \n

$user->profile()->associate($profile); \/\/ you want to associate a Profile to a User\n\n$user->save(); \/\/ Save the User\n \n

Problem with your method : Call to undefined method Illuminate\\Database\\Query\\Builder::associate() \n

And indeed, associate() method seems to be working but for belongsTo() relationships. \n

As my User model has a hasOne relationship on Profile, I have to use the following: \n

It is a belongsTo relationship. \n

Agreed, this is a belongsTo relationship between Profile and User. \n

$profile = new Profile([\n ‘my profile data . ‘\n]);\n\n$profile->user()->associate($user); \/\/ belongsTo relationship between Profile and User is set here\n\n$user->profile()->save($profile); \/\/ hasOne relationship between User and Profile should be set here\n$user->save();\n\ndump($profile->user); \/\/ I can retrieve my User this way. \ndump($user->profile); \/\/ . but still can’t retrieve my user’s profile :(\n \n»,»bodyInMarkdown»:»Agreed, this is a belongsTo relationship between Profile and User.\r\n\r\n«`php\r\n$profile = new Profile([\r\n ‘my profile data . ‘\r\n]);\r\n\r\n$profile->user()->associate($user); \/\/ belongsTo relationship between Profile and User is set here\r\n\r\n$user->profile()->save($profile); \/\/ hasOne relationship between User and Profile should be set here\r\n$user->save();\r\n\r\ndump($profile->user); \/\/ I can retrieve my User this way. \r\ndump($user->profile); \/\/ . but still can’t retrieve my user’s profile :(\r\n«`»,»replies»:[],»user»:<"id":31142,"username":"arnaud-xp","avatar":"\/\/www.gravatar.com\/avatar\/092d276a8f7643dd576c433a276b5f01?s=100&d=https%3A%2F%2Fs3.amazonaws.com%2Flaracasts%2Fimages%2Fforum%2Favatars%2Fdefault-avatar-27.png","experience":<"award_count":"0","level":1,"points":"645","pointsUntilNextLevel":"4,355">,»achievements»:[],»reported»:null,»profile»:<"github":"","twitter":"","full_name":null,"website":"","bio":null>,»dateSegments»:<"created_diff":"5 years ago">>,»likes»:[],»created_at»:»2015-10-28T12:31:08.000000Z»,»links»:<"delete":"\/discuss\/replies\/110132","like":"\/discuss\/replies\/110132\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110133,"conversation_id":22665,"body":"

If profiles table has the user_id then : \n

    \n
  • User hasOne Profile \n
  • Profile belongsTo User \n \n

Then you can do either : $user->profile()->save($profile) or $profile->user()->associate($user); $profile->save(); . \n

Ok I tried both methods separately and I still can’t retrieve a user’s profile like this : \n

Do you have a user that is signed in? Have you tried with dd($user->profile) ? \n

Both of them extends a Base model which is in the same namespace, itself extending \\Illuminate\\Database\\Eloquent\\Model \n

###Profile model \n

What do you get when you do the following: \n

$user = auth()->user();\n\n$user->profile()->create([\n .. put your attributes in here\n]);\n \n

Then do (in another request as pmall pointed out) \n

The relation is not yet loaded, just check if your tables are filled correctly instead of dding your $user->profile. It will be accessible on the next request when the user object gets reloaded. \n»,»bodyInMarkdown»:»The relation is not yet loaded, just check if your tables are filled correctly instead of dding your $user->profile. It will be accessible on the next request when the user object gets reloaded.»,»replies»:[],»user»:<"id":6695,"username":"pmall","avatar":"\/\/unavatar.now.sh\/github\/pmall","experience":<"award_count":"608","level":50,"points":"555,695","pointsUntilNextLevel":"0">,»achievements»:[],»reported»:null,»profile»:<"github":"pmall","twitter":"pmallinj","full_name":null,"website":"","bio":null>,»dateSegments»:<"created_diff":"7 years ago">>,»likes»:[],»created_at»:»2015-10-28T12:57:08.000000Z»,»links»:<"delete":"\/discuss\/replies\/110148","like":"\/discuss\/replies\/110148\/likes","best_answer":"\/discuss\/conversations\/22665\/best">,»best_answer»:false,»dateSegments»:<"createdDiff":"5 years ago">>,<"id":110149,"conversation_id":22665,"body":"

Ok it seems like everything was working since the beginning. As my profile was correctly saved in DB. \n

I simply had to redirect to another page and dump(auth()->user()->profile) worked as expected . \n

Источник

Читайте также:  Где отремонтировать тележку для сумки
Оцените статью