如何使用 id laravel 8 显示来自不同 table 的数据

how to display data from different table using id laravel 8

我有 2 tables,资产和历史。在 table 中,历史将承载 asset_id。 我想显示选中 asset_id 下的历史列表。 到目前为止我在 AssetController 中尝试过的内容:

public function edit(Asset $asset)
    {
        $phistories = (DB::table('phistories')->where('asset_id',$asset)->get()); 
        
        return view('assets.editAsset',[
            'asset' => $asset,
            'phistories' => $phistories
        ]);
    }

这是我的看法

 @foreach($phistories as $phistory)
      <tr>
        <td>{{$phistory->id}}</td>
        <td><a href="/edit/{{$phistory->id}}/editPhistory"><span>{{$phistory->phistory_name}}</span></a>
        </td>
        <td>{{$phistory->phistory_category}}</td>
        <td>{{$phistory->phistory_pic}}</td>
      </tr>
 @endforeach

我的问题是它没有在视图中显示任何内容。谁能检查我的查询是否正确或我使用了错误的方法?

假设您有一个名为 Assets 和 Phistories 的模型,您需要在这些模型中编写多对多关系。即

在您的资产模型中,添加此函数;

    public function phistories()
    {
        return $this->belongsToMany(Phistories::class);
    }

定义关系后,您可以使用资产控制器中的phistories动态关系属性访问历史记录:

use App\Models\Assets;
public function edit(Asset $asset)
    {

        $assets = Assets::with('phistories');
        
        return view('assets.editAsset',['assets' => $assets]);
    }

如果您希望能够从 Phistories 模型访问资产,请使用此选项

在您的 Phistories 模型中,添加此关系;

    public function Assets()
    {
        return $this->belongsToMany(Assets::class);
    }

现在,在您的视图中,您可以像这样访问 Phistories 数据,

@foreach($assets as $asset)
      <tr>
        <td>{{$asset->id}}</td>
        @foreach($asset->phistories as $phistory)
            <td>
               <a href="/edit/{{$phistory->id}}/editPhistory">
                 <span>{{$phistory->phistory_name}}</span>
               </a>
            </td>
        @endforeach
      </tr>

@endforeach

$phistories = (DB::table('phistories')->where('asset_id',$asset)->get());

改变

$phistories = (DB::table('phistories')->其中('asset_id',$asset)->get());

如果 $asset 是多个 ID

其次,请先尝试使用 get() 代替 get()