0

Всем привет. Подскажите пожалуйста как можно привязать таблицы между собой через отношения (Relasionship)? Я уже третий день не могу правильно реализовать отношение и проверить через функцию dd().

Например мне нужно из таблицы users привязать к таблице documents

1) В модели User

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

    public function document()
    {
        return $this->hasOne('App\Document');
    }

}

2) Создаю миграцию и модель Documents - Document

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

class DocumentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('documents', function (Blueprint $table) {
            $table->increments('id');
            $table->string('user_id');
            $table->string('title');
            $table->timestamps();
        });


    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::dropIfExists('documents');

    }
}




namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{

    public function user()
    {
        return $this->belongsTo('App\User');

    }

}

3) Теперь как нужно вывести информацию о пользователе id в document то есть user_id ?

4) Насколько я понял мне нужно создать controller DocumentController?

2 ответа 2

1

Если вам нужно получить информацию о user от документа то в модели Document еще указывайте

public function user() { return $this->belongsTo('App\User'); }

потом будете как обычно пользоваться

document->user

1
  • Еще можно указать уточнение по какому полю искать public function user() { return $this->belongsTo('\App\Document', 'user_id', 'id'); } вот тут еще можно посмотреть более подробно: link
    – zeloras
    28 янв 2018 в 8:14
1

в миграции user_id должен быть integer, так же можно сделать связку по полю с таблицей users.

Schema::create('documents', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    $table->string('title');
    $table->timestamps();
    });

Schema::table('documents', function($table){

    $table->foreign('user_id')
        ->references('id')->on('users')
        ->onDelete('cascade');

    });

создаете модель

namespace App;

use Illuminate\Database\Eloquent\Model;

class Doc extends Model
{
    protected $table = 'documents';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'user_id'
        ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];
}

создаете контроллер

use App\Http\Controllers\Controller;

class DocController extends Controller
{

    #GET
    public function index(Request $request)
    {
        $user_id = $request->get('user_id');

        $doc = App\Doc::select([
            'documents.id',
            'documents.title',
            'users.name as user_name', # инфо о пользователе
            ])
            ->join('users', 'users.id', '=', 'documents.user_id')
            ->where([
                ['user_id', $user_id]
            ])
            ->get();

        return view('ваш шаблон',$doc);
    }
}

Ваш ответ

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

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