[英]Problem with laravel relationships (many to many + one to many), cant access them for some reason
一個“用戶”有多個“輸入”,而“輸入”只有一個“習慣”和“情感”,所以我們可以說一個用戶有多個“習慣”和“情感”。
我應該可以做類似 {{$user->inputs->habitos}} 的事情,但由於某些原因我不能,而且 {{$users->input}} 可以工作並且 {{$input-> habitos}} 也可以,這里是代碼
用戶 model:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'telefone',
'hotmart_id'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function input(){
return $this->hasmany(Input::class, 'user_id', 'id');
}
}
輸入 model:
class Input extends Model
{
use HasFactory;
public function habito(){
return $this->belongsto(Habito::class, 'habito_id', 'id');
}
public function sentimento(){
return $this->belongsto(Sentimento::class, 'sentimento_id', 'id');
}
public function user(){
return $this->belongsto(User::class, 'user_id', 'id');
}
}
習慣 model:
class Habito extends Model
{
use HasFactory;
protected $fillable = ['nome', 'categoria'];
public function input(){
return $this->hasmany(Input::class, 'habito_id', 'id');
}
}
我一直在尋找有同樣問題的人,但我似乎什么也找不到,在此先感謝:)。
我有同樣的問題,嗯..幾乎一樣。 我的 Meals 有一個帶有標簽的 pivot 表 - 所以它是多對多的關系,標簽有翻譯。
想象一下,當獲取數據並使用查詢“with=tags”時,您實際上是根據區域設置(en、de、fr 等)獲取標簽翻譯,因此您 go 通過“meal_tag” pivot 表,通過“標簽” ”表,最后你會進入“tagtranslations”並獲取與餐點相關的 tag_id 的翻譯。
我認為您不必使用 has 我就是這樣做的:
用餐Class:
public function tags(){
return $this->belongsToMany(Tag::class, 'meal_tags')->withTrashed();
}
膳食標簽 class:
public function meals()
{
$this->hasMany(Meal::class, 'meal_id')->withTrashed();
}
public function tags()
{
$this->hasMany(Tag::class, 'tag_id')->withTrashed();
}
標簽 class:
public function meals()
{
return $this->belongsToMany(Meal::class, 'meal_tags')->withTrashed();
}
public function translations()
{
return $this->hasOne(TagTranslation::class)->where('locale', app()->getLocale())->withTrashed();
}
**忽略翻譯的中間件,因為你不需要它,如果你使用 softDeletes,只需使用 withTrashed
最后是 TagTranslations class:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
class TagTranslation extends Model
{
use HasFactory, SoftDeletes, HasRelationships;
public function tag(){
return $this->belongsTo(Tag::class)->withTrashed();
}
public function meals(){
return $this->hasManyDeep(Meal::class, [Tag::class, 'tag_id','meal_id'])->withTrashed;
}
}
注意我正在使用 hasManyDeep,因為你必須安裝 staudenmeir package:單擊此處查看 github .. 但問題是,即使沒有 hasManyDeep,Eloquent 也應該識別你需要的一切,但如果它像那樣工作,我是誰爭辯:D
這對我有用 - 如果出現問題,我確信這只是一些輕微調整的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.