我有一个sushi模型(电话),它与一个常规模型(用户)有关系。
寿司支持与常规模型的关系。
这是一种单向关系:电话链接到用户,但用户模型不知道任何关于电话的信息(即,没有user_id列,并且没有电话hasOne方法)。
预期结果:
App\Models\Sushi\Phone::find(1)->user
//用户1- (不需要:(x月1日至1x日)
当User是常规模型(使用默认迁移)时,我收到一条错误消息。
当User模型是sushi模型时,它工作得很好。
错误信息:
[41m Illuminate\Database\QueryException [49m SQLSTATE[HY000]: General error: 1 no such table: users (Connection: App\Models\Sushi\Phone, SQL: select * from "users" where "users"."id" = 1 limit 1).
建议?Phone
模型(寿司)
namespace App\Models\Sushi;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Phone extends Model
{
use \Sushi\Sushi;
protected $rows = [
['id' => 1, 'number' => '123', 'user_id' => 1],
['id' => 2, 'number' => '456', 'user_id' => null],
['id' => 3, 'number' => '789', 'user_id' => 2],
];
// App\Models\Sushi\Phone::find(1)->user
public function user(): BelongsTo
{
// works when referring to another Sushi model
// return $this->belongsTo(\App\Models\Sushi\User::class);
// fails when referring to regular Model: no such table users
return $this->belongsTo(\App\Models\User::class);
}
}
User
模型(寿司)
<?php
namespace App\Models\Sushi;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
class User extends Model
{
use \Sushi\Sushi;
// need one way relationship: App\Models\Sushi\Phone::find(1)->user
// don't need reverse relationship: App\Models\Sushi\User::find(1)->phone
// so: no phone_id column in model, and no phone relationship method
protected $rows = [
['id' => 1, 'name' => 'User 1'],
['id' => 2, 'name' => 'User 2'],
['id' => 3, 'name' => 'User 3'],
];
}
1条答案
按热度按时间vmdwslir1#
它在当前版本的Sushi中不起作用。我为此提交了一个PR,但它从未被合并:https://github.com/calebporzio/sushi/pull/98/
这背后的原因是Laravel假设相关模型与定义关系的数据库在同一个数据库中,除非您显式地设置相关模型的连接名称。
导致此行为的代码位于Laravel核心中:https://github.com/laravel/framework/blob/be2ddb5c31b0b9ebc2738d9f37a9d4c960aa3199/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php#L791
作为一种解决方法,您可以将其添加到
Phone
模型中: