Laravel 一对一关系无效只显示空消息
Laravel one to one relationship not work only show null message
我的数据库中有 2 个 table 并试图从中获取数据,这是我的数据库模式:
--------------- ---------------
| pg | | phone |
=============== ===============
| id | | id |
| name | | telp |
| address | | pg_id |
=============== ===============
phone table属于pg,我有这样的pg模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pg extends Model{
protected $table = "pg";
public function telepon(){
return $this->hasOne('App\Models\Phone', 'pg_id', 'id');
}
}
这是我的 phone 模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model{
protected $table = "phone";
public function pg(){
return $this->belongsTo('App\Models\Pg', 'pg_id', 'id');
}
}
这是我在 Controller 中获取数据的代码:
$pg = Pg::find(1);
return view('inpform', ['data' => $pg]);
在我的视图中,我转储了数据但结果为 NULL,如果我将代码更改为:
$pg = Pg::all();
return view('inpform', ['data' => $pg]);
它只显示来自 table pg 的数据,我想要它们之间的关系。
您已定义关系,但这并不自动意味着它们将与模型相关联。您有两种选择来预加载这些关系。您可以更改控制器代码以请求加载关系:
$pg = Pg::with('telepon')->find(1);
// or
$pg = Pg::with('telepon')->get();
或者,如果您始终需要此数据,可以将其添加到模型的 $with
属性。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pg extends Model
{
protected $table = "pg";
public function telepon()
{
return $this->hasOne(Phone::class);
}
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['telepon'];
}
这将导致每次访问任何 Pg
模型时都会加载关系。
我的数据库中有 2 个 table 并试图从中获取数据,这是我的数据库模式:
--------------- ---------------
| pg | | phone |
=============== ===============
| id | | id |
| name | | telp |
| address | | pg_id |
=============== ===============
phone table属于pg,我有这样的pg模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pg extends Model{
protected $table = "pg";
public function telepon(){
return $this->hasOne('App\Models\Phone', 'pg_id', 'id');
}
}
这是我的 phone 模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model{
protected $table = "phone";
public function pg(){
return $this->belongsTo('App\Models\Pg', 'pg_id', 'id');
}
}
这是我在 Controller 中获取数据的代码:
$pg = Pg::find(1);
return view('inpform', ['data' => $pg]);
在我的视图中,我转储了数据但结果为 NULL,如果我将代码更改为:
$pg = Pg::all();
return view('inpform', ['data' => $pg]);
它只显示来自 table pg 的数据,我想要它们之间的关系。
您已定义关系,但这并不自动意味着它们将与模型相关联。您有两种选择来预加载这些关系。您可以更改控制器代码以请求加载关系:
$pg = Pg::with('telepon')->find(1);
// or
$pg = Pg::with('telepon')->get();
或者,如果您始终需要此数据,可以将其添加到模型的 $with
属性。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pg extends Model
{
protected $table = "pg";
public function telepon()
{
return $this->hasOne(Phone::class);
}
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['telepon'];
}
这将导致每次访问任何 Pg
模型时都会加载关系。