【问题标题】:Laravel Snippets (v.1.13.0): Problems with relationships (One-To-Many, ...)Laravel Snippets (v.1.13.0):关系问题(一对多,...)
【发布时间】:2021-11-15 22:05:20
【问题描述】:

简介 我正在将此附加组件用于 Visual Studio Code。 与它建立关系时。我的观点似乎行不通。我在浏览器中遇到错误(见下文)。

Laravel 片段 ID:onecentlin.laravel5-sn-ps Laravel sn-ps for Visual Studio Code(支持 Laravel 5 及更高版本) 版本:1.13.0 Herausgeber:Winnie Lin Link zum Visual Studio 市场:https://marketplace.visualstudio.com/items?itemName=onecentlin.laravel5-snippets

我的模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    use HasFactory;
    protected $fillable = [];

    /**
     * Get the phone associated with the Person
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function phone(): HasOne
    {
        return $this->hasOne(Phone::class);
    }
}

调用视图时浏览器显示的错误

App\Models\Person::phone() 的 TypeError 返回值必须是 App\Models\HasOne,实例 Illuminate\Database\Eloquent\Relations\HasOne 返回(查看: C:\Users\MusaSaglam\componenttest\resources\views\test\index.blade.php)

我的看法

<x-layout>

    <main class="main" id="top">
      <div class="container" data-layout="container">
        <script>
          var isFluid = JSON.parse(localStorage.getItem('isFluid'));
          if (isFluid) {
            var container = document.querySelector('[data-layout]');
            container.classList.remove('container');
            container.classList.add('container-fluid');
          }
        </script>
  
        <x-nav.admin-nav/>
        <div class="content">
            <x-nav.admin-nav-top/>

            <h1>People</h1>
            @foreach ($people as $person)
                <h2>{{ $person->id }}</h2>
                <h2>{{ $person->phone->number }}</h2>
            @endforeach


        </div>
      </div>
    </main>
  </x-layout>

但如果我在模型中的 public function phone() 之后删除 : HasOne。一切正常。

两个问题

  • 为什么 Snippet 添加 : HasOne。这样做有什么好处?
  • 没有 : HasOne 的情况下,像我这样使用 sn-p 的用户不会更容易吗? 我是初学者,我不明白为什么这些教程不起作用。

【问题讨论】:

    标签: laravel visual-studio-code relationship


    【解决方案1】:

    可以参考类型声明https://www.php.net/manual/en/language.types.declarations.php

    1. 为什么代码段会添加:HasOne。这样做有什么好处?
    • 它是方法的返回类型并且是标准的,因此 VS 代码插件为您提供了符合行业标准的 sn-p(code)。
    1. 如果没有:HasOne,像我这样使用 sn-p 的用户不会更容易吗?我是初学者,我不明白为什么这些教程不起作用。
    • 这个 sn-p 可以工作,不用担心。只需在类初始化之前声明 HasOne,如 use Illuminate\Database\Eloquent\Relations\HasOne,它应该可以工作。

    顺便说一下,类型提示是可选的,所以如果你只删除 :HasOne(return type of method),sn-p 就可以工作。你已经尝试过了。

    【讨论】:

    • 完美。在声明它并(在函数之后重写它)之后,一切都按原样工作。并感谢您的解释。
    • 快乐编码 :)
    猜你喜欢
    • 2019-11-25
    • 2014-11-11
    • 2014-02-17
    • 2015-09-14
    • 2019-05-06
    • 2014-05-24
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多