Laravel关系没有结果

时间:2017-02-16 13:53:59

标签: php laravel laravel-5 eloquent laravel-5.2

我有一个"预订"与市场有关系的#34;和#34;摊位"

我有选择在创建表单上工作,但索引刀片未正确显示。

它应该采用" id"并将其转换为" name"字段如下所示

 <td>{{$user->role ? $user->role->name : 'User has no role'}}</td>

使用以下模型代码正确显示:     公共职能角色(){

    return $this->belongsTo('App\Role');
}

这是我的&#34;预订&#34;型号:

public function marketdate(){

    return $this->belongsTo('App\Markets');
}

public function stallstype() {

    return $this->belongsTo('App\Stalls');
}

在index.blade上有以下内容:

...
<td>{{$booking->marketdate ? $booking->marketdate->date : '-' }}</td>
<td>{{$booking->stallstype ? $booking->stallstype->name : '-'}}</td>
...

但这只是显示&#34; - &#34;当它呈现页面时

存储在数据库中的ID是正确的并且关联它只是没有正确显示。

另一件事,表模式如下:

摊位表:

Schema::create('stalls', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('cost');
        $table->timestamps();
    });

市场表:

  Schema::create('markets', function (Blueprint $table) {
        $table->increments('id');
        $table->string('date');
        $table->integer('is_active');
        $table->timestamps();
    });

错误是:

at PhpEngine-    >evaluatePath('C:\xampp\htdocs\moowoos\storage\framework\views/3bcb71b43fffee7f9 a9edf18bfb397ab94380507.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'bookings' => object(Collection), 'markets' => array('Saturday 4th March', 'Saturday 5th April', 'Saturday 6th May', 'Saturday 7th June', 'Saturday 8th July', 'Saturday 8th July'), 'stalltype' => array('Preloved', 'Craft', 'Business'))) in compiled.php line 15361
at CompilerEngine->get('C:\xampp\htdocs\moowoos\resources\views/admin/bookings/index.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'bookings' => object(Collection), 'markets' => array('Saturday 4th March', 'Saturday 5th April', 'Saturday 6th May', 'Saturday 7th June', 'Saturday 8th July', 'Saturday 8th July'), 'stalltype' => array('Preloved', 'Craft', 'Business'))) in compiled.php line 15193

这表明它正在返回数组

1 个答案:

答案 0 :(得分:0)

似乎Eloquent无法加载相关模型。当您使用 lists()加载其他模型时,我假设您对商业模式执行相同操作。

当您拨打列表(&#39;名称&#39;,&#39; id&#39;)时,您告诉Eloquent仅从数据库中加载这两个字段。因此,如果您也使用它来加载商业模式,那么您不会提取 marketdate_id stallstype_id ,这就是为什么Eloquent无法加载相关模型。

如果要加载相关模型,请确保将外键列传递给 lists()方法:

Business::lists('name', 'id', 'stalltype_id', 'marketdate_id')->all();