0

Laravel. Не могу получить данные по внешнему ключу. В базе всё хорошо, но постоянно получаю null. MemsController:

namespace App\Http\Controllers\Mems;

use App\Repository\MemsRepository;
use App\Repository\UsersRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Mems\BaseController;
public function __construct()
{
    $this->memsRepository = app(MemsRepository::class);
    $this->usersRepository = app(UsersRepository::class);
}

public function index()
{
    if(!\App\Http\Controllers\Mems\BaseController::checkAuth()){
        return redirect('/');
    }

    $mems = $this->memsRepository->showAllMems();
    dd($mems);

    return view('mems.index', compact('mems'));
}

MemsRepository:

<?php

namespace App\Repository;



use Illuminate\Database\Eloquent\Collection;
use App\Models\Mems as Model;
use Illuminate\Pagination\LengthAwarePaginator;

public function showAllMems(){
    $columns = [
        'id',
        'author_id',
        'img',
        'is_published',
    ];

    $result = $this->startConditions()
        ->select($columns)
        ->orderBy('id', 'DESC')
        ->with(['user:id,name,avatar'])
        ->paginate(25);

    return $result;
}

Mems(Model):

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;



class Mems extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'id',
        'img',
        'author_id',
        'is_published',
    ];

    public function user()
    {
        // У наказания есть причина
        return $this->belongsTo(User::class);
    }
}

User(Model):

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{


    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id','name', 'avatar','access_moderation', 'access_mems', 'access_admin', 'password','user_id', 'public_post',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */

}

Вот что получаю если ставлю dd перед отображением шаблона:

LengthAwarePaginator {#290 ▼
  #total: 1
  #lastPage: 1
  #items: Collection {#287 ▼
    #items: array:1 [▼
      0 => Mems {#286 ▼
        +timestamps: false
        #fillable: array:4 [▶]
        #connection: "mysql"
        #table: "mems"
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:4 [▶]
        #original: array:4 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: array:1 [▼
          "user" => null
        ]
        #touches: []
        #hidden: []
        #visible: []
        #guarded: array:1 [▶]
      }
    ]
  }
  #perPage: 25
  #currentPage: 1
  #path: "http://127.0.0.1:8888/mems"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

1 ответ 1

0

Мне кажется, Вы не верно указали связи (хотя вроде при этом должна быть ошибка).

public function user()
    {
        // У наказания есть причина
        return $this->belongsTo(User::class);
    }

При такой связи внешний ключ в таблице Mems должен быть user_id, у Вас же, судя по запросу author_id

$columns = [
        'id',
        'author_id',
        'img',
        'is_published',
    ];

    $result = $this->startConditions()
        ->select($columns)
        ->orderBy('id', 'DESC')
        ->with(['user:id,name,avatar'])
        ->paginate(25);

Т.е. надо исправить на :

return $this->belongsTo(User::class,'author_id');

Либо если user_id в таблице mems есть, то его надо указать в выбираемых столбцах:

$columns = [
            'id',
            'user_id',
            'author_id',
            'img',
            'is_published',
        ];
1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.