繁体   English   中英

Laravel 6 与 function 未显示相关数据

[英]Laravel 6 with function not showing related data

我在 Laravel 6 中制作了一个非常简单的 function,它使用 with():

$forms = Form::with('itemsForms')->get();

        return response()->json([
            'code' => 200,
            'data' => $forms
        ]);

下面是Form和ItemsForm之间的关系:

//Form
protected $fillable = [
        'title',
        'subtitle',
        'text',
        'name',
        'email',
        'phone_number',
        'address',
        'board',
        'date',
        'file',
        'purchasable',
        'payment_for',
        'invoice_amount',
    ];

protected $visible = [
        'title',
        'subtitle',
        'text',
        'name',
        'email',
        'phone_number',
        'address',
        'board',
        'date',
        'file',
        'purchasable',
        'payment_for',
        'invoice_amount',
    ];

public function itemsForms()
    {
        return $this->hasMany('App\ItemsForm');
    }
//ItemsForm
protected $fillable = [
        'item_id', 'form_id'
    ];

public function form()
    {
        return $this->belongsTo('App\Form', 'form_id');
    }

问题是它不会从 ItemsForm 中检索任何数据。 这是我尝试过的一些方法:

  • 我尝试将参数更改with其他类似的名称,但在每种情况下,我都会收到“找不到关系”或类似的错误。 当我使用itemsForms时,我没有收到任何错误。
  • 我尝试调试它以启用查询日志。 这是我得到的:
array:2 [
  0 => array:3 [
    "query" => "select * from `forms`"
    "bindings" => []
    "time" => 5.77
  ]
  1 => array:3 [
    "query" => "select * from `items_forms` where `items_forms`.`form_id` in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)"
    "bindings" => []
    "time" => 1.03
  ]
]
  • 我尝试获取ItemsForm数据,它可以毫无问题地检索它( ItemsForm::all() )。

知道是什么原因造成的吗?

编辑:ItemsForm 的架构如下:

Schema::create('items_forms', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('item_id');
            $table->unsignedBigInteger('form_id');
            $table->foreign('item_id')
                  ->references('id')->on('items')
                  ->onDelete('no action')
                  ->onUpdate('no action');
            $table->foreign('form_id')
                  ->references('id')->on('forms')
                  ->onDelete('no action')
                  ->onUpdate('no action');
        });

改变关系如下.. 在表格 class

public function itemsForms()
{
    return $this->hasMany('App\ItemsForm','form_id','id');
}

在 ItemsForm 中

public function form()
{
    return $this->belongsTo('App\Form', 'id','form_id');
}

您可以将关系用作

 $res = Form::find($id);
 foreach($res->itemsForms as $item)
 {
  echo $item->item_id;
 }

我终于发现了问题所在。

问题是我没有在visible数组中包含itemsForms (即使它不是数据库字段的一部分)。

没有特别的理由在我的案例中包含visible数组,所以我删除了它,但如果我想保留它,我应该将itemsForms作为数组的元素包含在内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM