【问题标题】:Trouble creating Laravel relationship无法创建 Laravel 关系
【发布时间】:2021-08-18 07:45:06
【问题描述】:

所以我正在尝试将计划与当前用户相关联。 我有模式和迁移称为计划。我有一个名为 user 的方法,我使用 belongsTo() 来获取与该计划关联的所有用户。我不确定为什么它不起作用 模态

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Plan extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'slug',
        'stripe_plan',
        'cost',
        'description'
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }

}

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePlansTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('plans', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('stripe_plan');
            $table->float('cost');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('plans');
    }
}

我从我的控制器调用计划模型

controller that calls the model

the view that i call the users method

显示空白

the output on the screen

【问题讨论】:

  • 邮政编码不是图片。没有显示任何内容,因为您没有将用户附加到计划中。由于您在表plans 中没有属性user_id。您应该如何知道每个计划属于哪个用户?

标签: laravel relationship


【解决方案1】:

您没有加载关系。您可以使用with() 来实现此目的。

<?php 
// controller

class PlanController extends Controller {

    public function method(){
        $plans = Plan::with('user')->get(); 
        // Continue with Code
        // if you use compact to pass data to the view
        // else  $plans = Plan::all();
        // views('view_name', ['plans' => $plans] should word just fine
    }
}

【讨论】:

  • 您不必急于加载关系就可以在刀片中调用它。在刀片中调用属性-&gt;user 会加载关系。 with() 用于预加载(只用一个数据库查询加载所有用户)。
  • 谢谢!创造了这种关系。我的迁移中也没有外键来指向用户 ID。
  • @N69S 是的。但是当您通过compact 语句传递信息时,我认为您仍然无法访问 DBQuery
  • 是的,您有权访问,它仍然是 Plan 实例的集合。 compact 不会将其转换为数组。注意语法$plan-&gt;user。仍然是一个对象
猜你喜欢
  • 2020-04-13
  • 2020-05-08
  • 1970-01-01
  • 2020-04-04
  • 2020-10-18
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多