Сохранить несколько атрибутов для одного и того же объекта в Laravel


у Меня есть таблица, недвижимости другой атрибутов и создал таблицу imovel_atributo уже, что квартира может иметь несколько атрибутов. Создал models Недвижимости и Атрибут, нужно создать модель Imovel_atributo? Как могли бы сделать в методе store, чтобы сохранить несколько атрибутов в недвижимости?

Model Недвижимости:

<?php

namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
protected $fillable = [
    'nome', 'disponivel_venda', 'valor_venda', 'disponivel_locacao', 'valor_locacao', 'descricao', 'observacao', 'dormitorios', 'garagens', 'area_util', 'area_total', 'novo', 'comercial', 'lancamento', 'cep', 'endereco', 'numero', 'complemento', 'bairro', 'cidade', 'estado', 'condominio', 'nome_condominio', 'fotos',
];

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

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

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

Атрибут Model:

<?php

namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
protected $fillable = [
    'nome',
];

public function property()
{
    return $this->hasMany('App\Property');
}

}

Controller Недвижимости:

<?php

namespace Imovan\Http\Controllers;
use Imovan\Property;
use Imovan\Type;
use Imovan\Attribute;
use Imovan\Owner;
use Imovan\Http\Requests\PropertyRequest;

class PropertyController extends Controller
{
public function __construct()
{
    $this->middleware('auth');
    $types = Type::all(); //Passa variaveis para todas as views
    view()->share(compact('types')); //Passa variaveis para todas as views
    $attributes = Attribute::all();
    view()->share(compact('attributes'));
    $owners = Owner::all();
    view()->share(compact('owners'));
    $properties = Property::all();
    view()->share(compact('properties'));
}
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $properties = Property::all();
    return view('/property/index')->with('properties', $properties);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('/property/create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(PropertyRequest $request)
{
    $params = $request->all();
    $property = new Property($params);
    $property->save();
    return redirect()->action('PropertyController@index');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $property = Property::find($id);
    return view('/property/edit')->with('property', $property);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(PropertyRequest $request, $id)
{
    $params = $request->all();
    $property = Property::find($id);
    $property->update($params);
    return redirect()->action('PropertyController@index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $property = Property::find($id);
    $property->delete();
    return redirect()->action('PropertyController@index');
}
}
Author: Marcelo, 2016-11-30

1 answers

Отношения Laravel N:M

Отношения Много Многие (N:M) eloquent, не обязательное создание model этого отношения, когда речь идет правильно, используя belongsToMany находится простой вставки и удаления элементов интерфейса.

Создал models Imovel и Atributo, мне нужно создать модель Imovel_atributo?

Если вы хотите, чтобы до можно создавать, но, если отношения, которые только есть два ключа, то нет необходимости, eloquent уже есть операции в настройки интерфейса (belongsToMany), теперь, если таблица имеет несколько полей, это, если подумать, то все зависит от сценария, но, в сущности, нет никакой необходимости.

В вашем случае специальная настройка:

<?php namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
    protected $fillable = ['nome'];

    public function property()
    {
        return $this->hasMany('Imovan\Property');
    }

    public function imovel()
    {
        return $this->belongsToMany('Imovan\Imovel',
                                    'imovel_atributo', 
                                    'attribute_id', 
                                    'imovel_id');
    }

}

<?php namespace Imovan;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
    protected $fillable = [
        'nome', 'disponivel_venda', 
        'valor_venda', 'disponivel_locacao', 
        'valor_locacao', 'descricao', 'observacao', 
        'dormitorios', 'garagens', 'area_util', 'area_total', 
        'novo', 'comercial', 'lancamento', 'cep', 'endereco', 
        'numero', 'complemento', 'bairro', 'cidade', 'estado', 
        'condominio', 'nome_condominio', 'fotos'];

    public function attribute()
    {
        return $this->belongsToMany('Imovan\Attribute',
                                    'imovel_atributo',
                                    'imovel_id',
                                    'attribute_id');
    }

    public function type()
    {
        return $this->belongsTo('Imovan\Type');
    }

    public function owner()
    {
        return $this->hasOne('Imovan\Owner');
    }
}

inserir/Remover данных в отношениях простой пример будет выглядеть так:

Вставить элемент интерфейс:

$a = Attribute::find(1);
$b = Property::find(1);
if ($a)
{
   $a->Property()->attach($b->id);
}

Удалить элемент интерфейса:

$a = Attribute::find(1);
$b = Property::find(1);
if ($a)
{
   $a->Property()->detach($b->id);
}

Примечание: Если ваш namespace namespace Imovan model должно быть так, как и вы разместили App, обратите внимание на это.

Как вы могли бы сделать в методе store, чтобы сохранить несколько атрибутов imovel?

В запросе должны исходить array атрибуты должны быть введены в недвижимости и при записи imovel, объяснение положить в attach это array

$b = Property::find(1);
$b->attribute()->attach([array_do_atribute]);
//se for numa edição de registro pode utilizar sync no lugar attach
//tem a funcionalidade de verificar os que são inseridos e remover o que não
//fazem parte do array.

Пример minimo

inserir a descrição da imagem aqui


Authors

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authors extends Model
{

    protected $table      = 'authors';    
    protected $primaryKey = 'id';    
    protected $fillable   = ['name'];    
    public  $timestamps   = false;

    public function books()
    {        
        return $this->belongsToMany('App\Books',
                                    'booksauthors',
                                    'authorid',
                                    'bookid');
    }
}

Books

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Books extends Model
{    
    protected $table      = 'books';
    protected $primaryKey = 'id';
    protected $fillable   = ['title'];
    public  $timestamps   = false;
    public function authors()
    {        
        return $this->belongsToMany('App\Authors', 
                                    'booksauthors', 
                                    'bookid',
                                    'authorid');
    }
}

Вставить/Удалить

$a = Authors::find(2);
$b = Books::find(2);

Ввести в отношении:

$a->books()->attach($b1);
//ou
$a->books()->attach($b->id);

Удалить интерфейс:

$a->books()->detach($b);
//ou
$a->books()->detach($b->id);

Фильмография:

 7
Author: novic, 2019-11-08 17:31:11