【问题标题】:Laravel - Array to string conversionLaravel - 数组到字符串的转换
【发布时间】:2018-12-29 18:19:58
【问题描述】:

我正在尝试将相关应用程序显示为抽象,我使用了下面的代码但我收到了这个错误

Array to string conversion

我的控制器

public function show($A_ID){

  $abstract = Project::find($A_ID);

  // I believe the issue is caused by the line below but I am not sure what is wrong about it 

  $applications = Application::find($A_ID);
  return view('Abstracts.show')->with('abstract', $abstract)
                             ->with($applications);
}

编辑:(添加模型 v1.0 和 v1.1)

我的模型(v1.0)显示Array to string conversion的错误

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Traits\HasCompositePrimaryKey; 

class Application extends Model{


    //Table name
    protected $table = 'student_application';

    //composite key
    protected $primaryKey = array('A_ID', 'S_ID');
    protected $fillable = ['S_Justification' ];
    public $incrementing = false;}

我编辑的模型(V1.1)

    <?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use App\Traits\HasCompositePrimaryKey; 

    class Application extends Model{
    use HasCompositePrimaryKey; 


    //Table name
    protected $table = 'student_application';

    //composite key
    protected $primaryKey = array('A_ID', 'S_ID');
    protected $fillable = ['S_Justification' ];
    public $incrementing = false;}

我想指出,复合键是使用这个 answer 第二号声明的,目前有 59 票

我的观点是这样的

@if (count($applications)>0)
@foreach ($applications as $application)
<tr>
        <td><h5>{{$application->S_ID}}</h5></td>
</tr>
@endforeach
@else 
<p> This project has no applications </p>
@endif

【问题讨论】:

  • 您是否在模型中包含了所需的特征?
  • 是的,我已经包含了它,我也更新了模型代码,你现在可以通过包含特征看到它
  • 他用了一个find的方法,你也加进去了吗?
  • 我在traits文件中添加了find方法
  • hmm use Traits\HasCompositePrimaryKey; 应该在你的模型中,而不是在它之上!请确认

标签: php laravel laravel-5 eloquent


【解决方案1】:

您正在将字符串传递给视图。

return view('Abstracts.show')->with(['abstract'=> $abstract)];

试一试。

编辑: 或者你可以这样使用。

with(array('order' => function($query)

无论如何,您需要在此处传递数组。如果您只想使用 -&gt;with('abstract'); 您需要添加抽象函数。例如:

public function deliveries() {
       // this might be $this->hasOne... depends on what you need
     return $this->hasMany('Abstracts', 'conditions', 'id')->where('foo', '!=', 'bar');
    } 

【讨论】:

  • 我的摘要返回视图没有问题,应用程序的问题
  • 您可以对应用程序执行相同的操作。试一试。您可以在肯定有效的函数($query)中导入应用程序。
  • 你能否再澄清一下这一行with(array('order' =&gt; function($query) 我不知道在哪里以及如何使用它
【解决方案2】:

$applications 是您的控制器中的一个对象,但您正在访问 $applications 作为视图文件中的集合。你可以试试这个:

$applications = Application::where('id', $A_ID)->get();

return view('Abstracts.show', compact('abstract', 'applications'));

【讨论】:

  • 不幸的是,不起作用。我相信我在这一行的问题$applications = Application::find($A_ID);
  • $applications = Application::where('id', $A_ID)-&gt;get()
猜你喜欢
  • 2016-07-08
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 2017-01-14
  • 2020-09-10
  • 2018-05-10
  • 2017-05-10
相关资源
最近更新 更多