如何从 Laravel 5.4 中的多个表中检索数据

How to retrieve data from multiple tables in Laravel 5.4

我有两个 table,我想从它们中检索数据并将其传递给我的 table。

为此,我创建了 2 个具有一对一关系的模型:

[地址]

class Adress extends Model
{    
     public function KontoKorrent()
     {
         return $this->hasOne(KontoKorrent::class, 'Adresse');
     }
}

[KontoKorrent]

class KontoKorrent extends Model
{
     public function Adresse()
     {
        return $this->belongsTo(Adress::class,'Adresse');
     }
}

我的控制器是这样的:

class AdressesController extends Controller
{
   public function index()
   {
    $adresses = Adress::with('KontoKorrent')->paginate(2);
      return view('welcome', compact('adresses'));

   }
}

当我使用tinker App\Adress:: 每个 adress 都与 kontokorrent 相关。这是有效的。

  App\Adress {#698
         Adresse: "3030",
         Anrede: "Company",
         Name1: "A Company Name",
         LieferStrasse: "Dummystreet",
         KontoKorrent: App\KontoKorrent {#704
           Location: "1",
           Adresse: "3030",
           Kto: "S0043722",

在我看来:

<ul>
  @foreach($adresses as $adress)
    <li>{{ $adress->Name1 }}</li>    //this is working
    <li>{{ $adress->KontoKorrent->Kto }}</li>  //this is NOT working
  @endforeach
</ul>

{{ $adresses->links() }}

关系显示错误:

Trying to get property of non-object

我做错了什么?

您遇到的错误:

Trying to get property of non-object

与某些没有 KontoKorrentAdress 模型相关,那么您的 $adress->KontoKorrent returns null 和 null 不是一个对象,即消息的原因。

要修复它,您应该执行 if 检查 adress 是否有以下关系:

<ul>
  @foreach($adresses as $adress)
    <li>{{ $adress->Name1 }}</li>    //this is working
    <li>
        @if($adress->KontoKorrent)
            {{ $adress->KontoKorrent->Kto }}
        @else
            <!-- Put something here if you want, otherwise remove the @else -->
        @endif
    </li>  //this is NOT working
  @endforeach
</ul>

这可以缩短为:

{{ $adress->KontoKorrent ? $adress->KontoKorrent : 'the else content' }}

或者在PHP >= 7.0,你可以使用null coalesce运算符:

{{ $adress->KontoKorrent ?? 'the else content' }}