我試圖用PHP laravel做一個instagram的克隆。 我想在主頁上顯示帖子。
這是pageController.php:
class PagesController title">PagesController extends Controller
{
public function home() {
$posts = Post::all();
return view('pages.home', ['post' => $posts] )。
}
}
這是主頁視圖:
@foreach($posts as $post) {
<div>{{ $post->id }}</div>
// I want to get the post's owner data..
}
這就是帖子遷移檔案:
<?php
使用 Illuminate資料庫Migrations遷移。
使用 IlluminateDatabaseSchemaBlueprint。
use IlluminateSupportFacadesSchema;
class CreatePostsTable extends Migration
{
/**。
* 運行遷移。
*
* @return void
*/
public function up()
{
Schema::create('post', function (Blueprint $table) {
$table->id()。
$table->foreign('user_id')->references('id')->on('users') 。
});
}
}
用laravel eloquent可以嗎?
uj5u.com熱心網友回復:
你必須在Post.php中添加belongsTo關系,如:
public function users(){
return $this-> belongsTo(User::class);
}
而你可以像這樣訪問刀片檔案中的用戶資訊:
@foreach($posts as$post) {
<div>{{ $post->id }}</div>
// I want to get the post's owner data.
<h1>{{ $post->user()->get()->name }}</h1>
}
uj5u.com熱心網友回復:
你必須在模型上建立一個關系。 就像上面所說的那樣。 https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
而且你也可以做急切加載來加載用戶帖子的關系。
$posts = Post::with('user'/span>)->get()。
uj5u.com熱心網友回復:
是的, 這是可能的, 閱讀Laravel Eloquent關系檔案將是一個很好的開始. Laravel的檔案真的非常好。
除此之外...
你的遷移是不正確的,因為它缺少一個欄位來存盤user_id關系id。所以你需要添加這個欄位。
public function up()
{
Schema::create('post', function (Blueprint $table) {
$table->id()。
$table->unsignedBigInteter('user_id')。
$table->foreign('user_id')-> references('id')->on('users');
});
}
那么在你的User模型中,你將需要一個函式來回傳與User相關的Posts。在這種情況下,這是一個hasMany關系,因為一個User可以有manyPosts。
User.php
public function posts()
{
//一個用戶有很多帖子。
return $this->hasMany(Post::class)。
}
然后在Post模型上定義反函式,以獲得它所屬的User。
Post.php
public function User()
{
//一個帖子只屬于一個用戶。
return $this-> belongsTo(User::class);
}
現在你有一個遷移和在模型上定義的關系,你可以繼續使用它們。
讓我們假設你有下面的路由定義(使用Laravel 8的語法)。
Route::get('/posts', [PostController::class, 'index'])。
它呼叫了以下Controller和index函式。
PostController.php
class PostController
{
public function index()
{
///獲取帖子并急于加載相關的用戶。
$posts = Post::with('user')->get();
return view('post.index', compact('post')) 。
}
}
在你的刀片視圖中,你可以訪問Post的User,就好像它是Post的一個屬性。
posts/index. blade.php
@foreach ($posts as$post)
<p>{{ $post-> id }}</p>
<p>{{ $post-> user->name }}</p>
@endforeach
如果你想要隨機的 帖子,那么你可以使用inRandomOrder和limit來獲得一些,所以例如要獲得隨機的10 帖子。
$posts = Post:: inRandomOrder()->with('user')->limit(10)->get()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/324240.html
標籤:
上一篇:Laravel8提取包含重復的行
